how can I change only a param like an id in my URL - vue.js

I have a have a list of links inside a childcomponent which is integrated in different pages and if I click on a link, I need to get an id back, but I need to keep the current URL with the new id to call another method.
this.$router.push({path: '/page/', params: {id:id}})
this.$router.push({path: '/otherpage/', params: {id:id}})
I tried several things which are not working, like
this.$router.push({path: this.$router.currentRoute, params: {id:id}})
to get the following on different pages
http://domain/page/1
or
http://domain/otherpage/1
if I hardcode the path it works with:
this.$router.push(`/page/${id}`)
but I like to reuse the component on any page
thanks to Igor I ended up with the following:
const path = `/${this.path}/${node.id}`
if (this.$route.path !== path) this.$router.push(path)
thanks

From vue-router docs:
Note: params are ignored if a path is provided...
https://router.vuejs.org/guide/essentials/navigation.html
Instead of providing the path, you should call this.$router.push() with the route name, and the desired params.
For your example:
this.$router.push({name: this.$router.currentRoute.name, params: {id:id}})
This approach assumes that your routes are named, like this:
const routes = [
{
path: "/page/:id",
component: () => import('/path/to/component.vue'),
name: "nameOfTheRoute",
// other attributes
},
//...
]

Related

How to change base url in VUE router?

Current URL is 'https://localhost:3000/lang/countries/states/cities/'
I want to change it to:
https://localhost:3000/lang/compare/?c=1&back=1&query=94&query=911
Basically I want to edit the current URL. I tried using:
this.$router.push({
path:'/lang/compare/?c=1&back=1&query=94&query=911',
});
this.$router.replace({
path:'/lang/compare/?c=1&back=1&query=94&query=911',
});
But this changes the URL to :
https://localhost:3000/lang/countries/states/cities/lang/compare/?c=1&back=1&query=94&query=911',
I have tried using window location href but coz of that state of my variable is lost, hence I need to use VUE router for this. Is their any way to change base URL in VUE routes.
Your method is also right it should work if there is no other issue,
try with
this.$router.push({ path: '/lang/compare', query: { c: 1,back:1,firstquery:94,queryB:991}})
or you can also try with $router name defining a name on router index file
{
path: "/lang/compare",
name: "compare",
component: comparePage,
},
this.$router.push({ name: 'compare', query: { c: 1,back:1,firstquery:94,queryB:991}})

Optional route params with Vue Router

In my Vue 2.7.5 app (using Vue Router 3.5.4) I'm trying to define this route
{
path: '/messages/:messageId?/replies/:replyId?',
name: 'messages',
component: () => import('#/views/messages')
}
The intent is
to see all messages use /messages
to see a specific message use /messages/:messageId
To see a specific message and a specific reply to that message use /messages/:messageId/replies/:replyId
However, if I navigate to this route without specifying any route params using
<router-link :to="{name: 'messages'}">
Then the URL is resolved as /messages/replies, but I would like it to be resolved as /messages.
Essentially, what I want is: don't include /replies unless there's a replyId param, but I don't know how to express that.
One solution is to use the following instead:
<router-link :to="{ path: '/messages'}">
But I prefer to always refer to routes by name, because this gives me the flexibility to change the paths without breaking anything
The easiest solution for you is to remove /replies and only have path like this:
'/messages/:messageId?/:replyId?'
(Optional solution)
If removing that part of url is not an option and using named routes is a must, here is an alternative solution where you use two named routes. If the replyId is missing you can redirect before enter to the 2nd named route.
{
path: '/messages/:messageId?/replies/:replyId?',
name: 'message-replies',
component: () => import('#/views/messages'),
beforeEnter({ params }) {
if (!params.replyId) {
return {
name: 'messages',
params: {
messageId: params.messageId,
},
};
}
},
},
{
path: '/messages/:messageId?',
name: 'messages',
component: () => import('#/views/messages'),
},

Nuxt pass props programmatically, through router

i'm using Nuxt
I'm having troubles with passing data from one page to another
I would like programmatically to navigate to other page, and pass some data to other page (in this case its javascript object)
So here is my code so far:
I have a component in which I navigate from:
this.$router.push({ path: 'page/add', props: { basket: 'pie' } });
And here is a component where I would like to get data, its a Nuxt page:
export default {
components: { MyComponent },
props: [
'basket' // this is also empty
],
async asyncData(data) {
console.log(data); // data does not contain basket prop
},
meta: {
breadcrumb: {
path: '/page/add',
},
},
};
</script>
But when I try to acces props, or data or data.router it does not contain basket prop ??
Also, I would not like to use query, or params because they change URL
[1]: https://nuxtjs.org/
You can use localstorage and save you'r data in it:
localStorage.setItem("nameOfItem", Value);
and delete it if you want after you'r done with it:
localStorage.removeItem("nameOfItem");
If you don't want to use query or params, I would check out the vuex store. Its a really cool way of storing global variables and use it in multiple pages.
Vuex store
Navigate to a different location
To navigate to a different URL, use router.push. This method pushes a new entry into the history stack, so when the user clicks the browser back button they will be taken to the previous URL.
The argument can be a string path, or a location descriptor object. Examples:
// literal string path
this.$router.push('/users/eduardo')
// object with path
this.$router.push({ path: '/users/eduardo' })
// named route with params to let the router build the url
this.$router.push({ name: 'user', params: { username: 'eduardo' } })
// with query, resulting in /register?plan=private
this.$router.push({ path: '/register', query: { plan: 'private' } })
// with hash, resulting in /about#team
this.$router.push({ path: '/about', hash: '#team' })
reference:
https://router.vuejs.org/guide/essentials/navigation.html#navigate-to-a-different-location
To navigate to a different URL, use router.push. This method pushes a new entry into the history stack, so when the user clicks the browser back button they will be taken to the previous URL.
What you are trying to accomplish is not conform with the browser (history etc.) or
http protocol (GET/POST).
Also, when using path params and other variables, such will be ignored, as per the documentation.
Note: params are ignored if a path is provided, which is not the case for query, as shown in the example above. Instead, you need to provide the name of the route or manually specify the whole path with any parameter.
Using props here is very likely the wrong approach, as you will never get that data to the component.

Custom handling forward slashes in vue router ids

I have a use case for needing the id part of a vue route to contain unescaped forward slashes.
My current route looks like this:
{
path: '/browse/:path*',
component: browse,
name: 'browse',
displayName: 'Browse',
meta: { title: 'Browse' },
},
So when a user browses to the above url, the browse component is shown.
However, i want to use the id part of the path (:path*) to contain a nestable fielsystem like path to be consumed by my browse page.
For example the url /browse/project/project1 would take me two levels down in my tree to the project1 item.
Now, the problem i'm running into is that vue router is escaping my ids (path) when navigating programatically, and my url ends up like this: /browse/project%2Fproject1. This is non-ideal and does not look nice to the end user. Also, if the user does browse to /browse/project/project1 manually the app will work correctly and even keep the original encoding in the url bar.
So i could resolve this my making an arbitrary number of child paths and hope that the system never goes over these, but thats not a good way to solve my problem.
I should also clarify that the application will not know anything about the path after /browse as this is generated dynamically by the api that powers the app.
Is there a native way in vue-router to handale this? or should i change up how im doing things.
There is a more elegant solution without workarounds.
Vue router uses path-to-regexp module under the hood and constructions like
const regexp = pathToRegexp('/browse/:path*')
// keys = [{ name: 'browse', delimiter: '/', optional: true, repeat: true }]
https://github.com/pillarjs/path-to-regexp#zero-or-more
const regexp = pathToRegexp('/browse/:path+')
// keys = [{ name: 'browse', delimiter: '/', optional: false, repeat: true }]
https://github.com/pillarjs/path-to-regexp#one-or-more
set repeat flag to true. Any array parameter with repeat flag will be joined with the delimiter (default '/').
So you can pass a splitted array ['project','project1'] instead of 'project/project1' into router.push():
router.push( {name: 'browse', params: {path: ['project','project1']}} );
or
router.push( {name: 'browse', params: {path: 'project/project1'.split('/')}} );
So I managed to 'fix' this with a bit of a hack.
When creating my Vue router instance I am attaching a beforeEach function to replace any outgoing encodings of '/'. This will send the 'correct' URL I am looking for to the client.
const router = new Router({
mode: 'history',
routes,
});
router.beforeEach((to, from, next) => {
// hack to allow for forward slashes in path ids
if (to.fullPath.includes('%2F')) {
next(to.fullPath.replace('%2F', '/'));
}
next();
});
I just stumbled over your question while facing a similiar problem.
Think this is because an id shall identify one single resource and not a nested structure/path to a resource.
Though I haven't solve my problem yet, what you probably want to use is a customQueryString:
https://router.vuejs.org/api/#parsequery-stringifyquery
https://discourse.algolia.com/t/active-url-with-vue-router-for-facet-and-queries/3399
I fixed it by creating helpers for generating hrefs for :to attributes of vue router link.
First i made router accessible for my new helper service like here Access router instance from my service
Then i created router-helpers.js and here i made my helpers, here is an example
import Vue from 'vue'
import router from '../router.js'
// replace %2F in link by /
const hrefFixes = function(to) {
return to.replace(/%2F/g, '/')
}
// my link helper
Vue.prototype.$linkExample = attr => {
// create "to" object for router resolve
const to = { name: `route-name`, params: { param1: attr } }
// this will resolve "to" object, return href param as string
// and then i can replace %2F in that string
return hrefFixes(router.resolve(to).href)
}
Just include this service once in your Vue application an then just use this helper like this
<router-link :to="$linkExample(attr)">text</router-link>

How to use vue-router params

I'm new to Vue now working with its router.
I want to navigate to another page and I use the following code:
this.$router.push({path: '/newLocation', params: { foo: "bar"}});
Then I expect it to be on the new Component
this.$route.params
This doesn't work.
I also tried:
this.$router.push({path: '/newLocation'});
this.$router.push({params: { foo: "bar"}});
I've inspected the source code a bit and noticed this property gets overwritten with a new object {}.
I'm wondering is the params use is other than I think?
If not, how to use it?
Since you want to pass params to the component of the respective route you route object's path property should have a dynamic segment denoted by : followed by the name of the key in your params object
so your routes should be
routes: [
{path: '/newLocation/:foo', name: 'newLocation', component: newComponent}
]
Then for programmatically navigating to the component you should do:
this.$router.push({name: 'newLocation', params: { foo: "bar"}});
See that I am using name of the route instead of path as you are passing params by the property params.
if you want to use path then it should be:
this.$router.push({path: '/newLocation/bar'});
by the path approach the params will automatically map to corresponding fields on $route.params.
Now if you console.log(this.$route.params) in your new component you will get the object : {"foo": "bar"}
Try using query instead of params
this.$router.push({path: '/newpath', query : { foo: "bar"}});
And in your component
console.log(this.$route.query.foo)
The easiest way I've found is to use named routes along with the params options. Let's say you have a router file that looks like this:
And you want to reach the "movie" page with some ID. You can use Vue's router link component (or Nuxt's link component) to reach it like this:
Vue:
<router-link :to="{ name: 'movie', params: { id: item.id } }">{{ item.title }}</router-link>
Nuxt:
<nuxt-link :to="{ name: 'movie-id', params: { id: item.id } }">{{ item.title }}</nuxt-link>
Note that the name parameter must match the "name" attribute of the desired route in the router file. And likewise, the parameter name must match.
Nuxt creates the route file for you automatically when you create a
new page. To see what name Nuxt gives its routes, go to the .Nuxt
folder in your project and look for a "router.js" file
Isn't it generally considered an anti pattern to bind the properties to the router?
It's a much more DRY solution to have them bind to the component it's self, which I actually believe the Vue router does. Please see: https://router.vuejs.org/en/essentials/passing-props.html for more info on the best practices here
Can you try accepting the property in the props: [] property of your component? You can see how to do that here: https://v2.vuejs.org/v2/guide/components.html#Props
Please do pop up if you have any questions! Happy to help further.