How to change base url in VUE router? - vue.js

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}})

Related

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'),
},

how can I change only a param like an id in my URL

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
},
//...
]

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.

Vue router not matching route with more than one slash

basically my issue is that I want to pass a router prop called name into an article route, so something like /article/:name. When I direct to that route internally, like with $router.push(name: 'article', params: {name: 'something'}), it works just fine. But when I then use that url, /article/something, the route doesn't match and the page is blank.
But if I just use /:name instead of /article/:name, everything works just fine. Does anyone have any idea why the /article part could be causing the route to fail to match? Thanks in advance.
EDIT: Route definition:
{
path: '/article/:name',
name: 'article',
component: () => import('../views/Article.vue'),
props: true,
}
When I navigate to /article/something, the page is blank, no matter what something is. But if I have the following route definition:
{
path: '/:name',
name: 'article',
component: () => import('../views/Article.vue'),
props: true,
}
and navigate to /something, it works just fine.

Data passing using props in router is not working

I am trying to send data from one vue component to another by using props in router. but it is not working. whenever i try to log the props it outputs undefined. code is given below
From where data is sending
Where receiving
in index.js. router setting
None of the code you've posted matches up.
Firstly, the console logging should be just console.log(this.myprops). The point of using props is that you don't need to reference the router itself, e.g. via $router.
Next problem, you're mixing path and params. That isn't allows. See https://router.vuejs.org/guide/essentials/navigation.html. params are for named routes.
I imagine what you're aiming for is something like this:
self.$router.replace({ name: 'DashboardPatient', params: { myprops: authUser.email } })
with router config:
{
path: '/patient',
component: Dash,
children: [
{
path: ':myprops', // <--- Adding myprops to the URL
name: 'DashboardPatient',
component: DashboardPatient,
props: true,
meta: { requiresAuth: true }
}
]
}
Keep in mind that routing is all about building and parsing the URL. So the value of myprops needs to be in the URL somewhere. In my example it comes at the end, so you'll get /patient/user#example.com as the URL. If it weren't in the URL then there'd be no way for the router to populate the prop if the user hit that page directly (or refreshed the page).
To hit the same route using a path instead of a name it'd be something like this:
self.$router.replace({ path: `patient/${encodeURIComponent(authUser.email)}` })
or even just:
self.$router.replace(`patient/${encodeURIComponent(authUser.email)}`)
Personally I'd go with the named route so that the encoding is handled automatically.
If you don't want to put the data in the URL then routing is not the appropriate way to pass it along. You'd need to use an alternative, such as putting it in the Vuex store.