replacing path using route object in nuxt - javascript

I want to go to this url:
myApp.com/search-page?name%5Bquery%5D=value
and the following code works well for it when I'm on the home page myApp.com:
this.$router.push({
path: "search-page",
query: { name: { query: `${this.value}` } }
});
But if I'm on a different page that has a path already like:
myApp.com/movies/id
when I use the same code with $router.push it takes me to this url:
myApp.com/movies/search-page?name%5Bquery%5D=value
As you can see there is an extra movies/ in the URL which we don't want! How can I make it so no matter what my current path (URL) is, my $router.push method takes me to:
myApp.com/search-page?name%5Bquery%5D=value

You are using path in $router.push. If you are in a nested page you also need to change the path value.
Instead use name so you don't have to specify path levels
this.$router.push({
name: "search-page",
query: { name: { query: `${this.value}` } }
});
In nuxt, the route names are basically the folder name generated to lower string and hyphens. So if you have folder like this and you want to access movies id route
pages/
--| movies
-----| _id.vue
You can access it by
this.$router.push({
name: "movies-id",
params: {
id: 1
}
});

Related

Vue emit data to router view component. Not emitting data and Form submission is cancelled error

I have an array called components at the LiveEdit.vue file data. I want to add an array item which has an object inside to the components array. Everything works fine except the emitting data part. LiveEdit component is on /live url path. The child i'm emitting is NavBarEdit.vue which is on /edit/nav url path. I want to emit data form NavBarEdit to LiveEdit. I also want to change url path to go back to LiveEdit component. I somehow found a way to change routes which is this
this.$emit('addComponent', data)
this.$router.push('/live')
This is my code at LiveEdit vue file
data() {
return {
components: []
}
},
methods: {
addComponent(data) {
this.components = [...this.components, data]
}
},
This is my routes
routes: [
{
path: '/',
component: LandingPage,
},
{
path: '/live',
component: LiveEdit,
},
{
path: '/edit/nav',
component: NavBarEidt,
},
{
path: '/edit/slider',
component: SliderEdit,
}
]
How can I solve this problem? I am really in a trouble with this one. I've been dealing with this like two days. And still no luck. So, please help me out

How to create a single Gatsby Page to show and filter all blog posts by tag/category

Hello i'm building a blog using Gatsby and Netlify CMS. I started off from the gatsby-starter-netlify-cms template.
I have the /blog page where i currently display all posts and also a list of all the tags.
When user clicks on a tag, it is currently redirected to the tags/name-of-tag page, where a list of all posts tagged like that is displayed.
What i want instead is to directly filter the list on the /blog page.
This way i'll have only one page to display and filter blog posts by tag (and possibly by term search).
So the tag links should redirect to /blog?tag-name or something like that.
I'm not sure how to tell Gatsby to create a single page with possibility to inject a filter value in order to pass it to the page query..
This is how /tags/ pages are created currently:
// Tag pages:
let tags = []
// Iterate through each post, putting all found tags into `tags`
posts.forEach((edge) => {
if (_.get(edge, `node.frontmatter.tags`)) {
tags = tags.concat(edge.node.frontmatter.tags)
}
})
// Eliminate duplicate tags
tags = _.uniq(tags)
// Make tag pages
tags.forEach((tag) => {
const tagPath = `/tags/${_.kebabCase(tag)}/`
createPage({
path: tagPath,
component: path.resolve(`src/templates/tags.js`),
context: {
tag,
},
})
})
This is my blog page query (the one i want to be able to filter by tag):
export const blogPageQuery = graphql`
query BlogPageTemplate {
markdownRemark(frontmatter: { templateKey: { eq: "blog-page" } }) {
frontmatter {
image {
childImageSharp {
fluid(maxWidth: 2048, quality: 80) {
...GatsbyImageSharpFluid
}
}
}
heading
subheading
}
}
allMarkdownRemark(
sort: { order: DESC, fields: [frontmatter___date] }
filter: { frontmatter: { templateKey: { eq: "blog-post" } } }
) {
edges {
node {
id
fields {
slug
}
excerpt(pruneLength: 180)
frontmatter {
date(formatString: "MMMM DD, YYYY")
title
description
featuredpost
featuredimage {
childImageSharp {
fluid(quality: 50, maxWidth: 512) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
}
}
`
I'm not sure how to tell Gatsby to create a single page with
possibility to inject a filter value in order to pass it to the page
query.
You can't. The only way to filter data in a page query is by passing data using the context. Like you are doing in with the tags page:
createPage({
path: tagPath,
component: path.resolve(`src/templates/tags.js`),
context: {
tag,
},
})
The easiest and native approach is to use the /tag/tag-name page, which is intended to filter by tag name, otherwise, you will need to get the URL parameter and using it in a JavaScript filter function to filter all the data from the page query. Since you are missing the rendering part of your blog page... Something like this approach should work:
const BlogTemplate=({ data }){
if(typeof window !== "undefined"){
const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const urlTag= urlParams.get('tag');
const filteredPosts= data.allMarkdownRemark.edges.node.filter(node=> node.frontmatter.tag.includes(urlTag))
const loopData= urlParams.has('tag') ? filteredPosts : data
}
return loopData.allMarkdownRemark.edges.node.map(node=> <h1 key={node.title}>{node.title}</h1>)
}
Note: of course, adapt it to your needs but get the idea.
Note also that you will need to wrap all your window logic in the typeof window !== "undefined" condition, since in the SSR window (and other global objects) are not available.
The key part is to use wether use data or your filteredPosts depending on the existance of the URL parameter, so if it exists, you will need to filter the data otherwise, you need to use the "default" data (unfiltered).
It's difficult to guess how the code will behave but the idea relies on changing your iterable data depending on the URL, use some hooks if needed.
According to your query, it seems that your blogs don't contain any tag field in the blog template query so you will need to add it to allow the filter loop to work.
Once the code is working, you will need to add the proper controls to avoid the code-breaking when some field is missing, but the idea and the path to follow is this.

Failed to get the parameter with Vue-Router in VueJs

I have 2 routes with vue-router, one of them receives a parameter id.
{
path: '/sale/',
name: 'other',
component: ComponentA,
},
{
path: '/sale/option/:id',
name: 'close-sale',
component: ComponentB,
},
it turns out that the redirection is done with code directly, making in ComponentA
this.$router.push({ name: 'close-sale', params: {id: this.id}})
When I do this, it redirects me to the path named close-sale, but inside the path I get the id to load some data of the following form
data(){
return {
id: this.$route.params.id
....
}
},
mounted (){
axios.get('...'+this.id). // undefinied this.id
},
But I always return undenifed for the value of id.
How could I get this id if in the url it is not shown? I hope I have understood

Supporting multiple parameters with nested properties in Meteor and Iron Router

Using Meteor and Iron Router, I've created dynamic page paths that use multiple parameters. However, if I attempt to access nested/child properties in my path, the route breaks. These posts were helpful but did not address child-properties:
Iron-router nested routes with multiple parameters
meteor iron-router nested routes
Iron Router
this.route('location',{
path: '/properties/:foo/:_id',
waitOn: function(){
return Meteor.subscribe('properties', this.params._id);
},
action: function(){
this.render('propertyPage', {
data: function(){
return Properties.findOne(this.params._id);
}
});
}
});
Markup (Works)
Click Me
When attempting to reference a nested property in the markup, it breaks:
Markup (NOT working)
Click Me
I also tried it inside of the javascript, with no luck:
path: '/properties/:foo.nestedChild/:_id',
Is there a way to reference a nested property without breaking Iron Router?
- - - Edit - - -
For a more practical example:
// data context from route action (Properties.findOne(this.params._id))
property = {
_id: "3cu7B8b6K3EzCgYnQ"
address: {
city: 'Houston',
state: 'TX',
zip: 77006,
lat: null,
lng: null
},
images: ['img1.png', 'img2.png', 'img3.png'],
schools: [
{ grade:'elementary', name:'Haude', rating:4 },
{ grade:'middle', name:'Strauke', rating:5 },
{ grade:'high', name:'Klein', rating:3 },
]
}
I'm trying to build out a url schema like this:
path: '/properties/:address.city/:address.state/:address.zip/:_id'
or in the example's case:
"/properties/Houston/TX/77006/3cu7B8b6K3EzCgYnQ"
In your route, you need to fetch :foo from the params object if you want to use it:
var foo = this.params.foo;
It's little too late, but somebody might benefit anyway. I solved it the following way:
Defining a nested path (BTW Defining paths this way is better for SEO)
Content
Router
this.route('playlistItem', {
path: '/user/:owner/playlist/:playlist',
onBeforeAction: function() {
// You can get your params
var ownerId = this.params.owner
var playlistId = this.params.playlist
// execute some code
},
});

How to generate a route without question mark on FOSJSRoutingBundle

Im confused, this is the documentation
https://github.com/FriendsOfSymfony/FOSJsRoutingBundle/blob/master/Resources/doc/index.md
documentation ->
Routing.generate('my_route_to_expose', { id: 10 }); // will result in
/foo/10/bar
this is the route on the controller (has the prefix "superuser")
/**
* #Route("/deleteuser/{userid}",name="suDeleteUserRoute",options={"expose"=true})
* #Template()
*/
public function deleteUserAction($userid)
{
so I obviously want to generate a route that looks like this
server.com/superuser/deleteuser/76
but it generates a route with a question mark instead
server.com/superuser/deleteuser?id=76
This is how I generate the route on Javascript
Routing.generate('suDeleteUserRoute', { id: 76 });
You can create the route in routing.yml something like this:
super_user:
path: /superuser/deleteuser/{userid}
defaults: { _controller: BundleName:ControllerName:FunctionName }
requirements:
userid: \d+
Controller Name should be without suffix Controller
Function Name should be without suffix Action
Your route uses the userid parameter but you are giving it the id parameter.
Try using Routing.generate('suDeleteUserRoute', { userid: 76 }); instead.

Categories

Resources