Vue3: How to send parameters to a route without adding them to the url in Vue3?
P粉465675962
P粉465675962 2023-12-11 13:07:20
0
1
488

In Vue3, is there a way to pass attributes to routes without displaying the value in the url?

I define the route like this:

{
    path: '/someRoute',
    name: 'someRoute',
    component: () => import('@/app/pages/SomeRoute.vue'),
    props: (route) => {
            ...route.params
        }, // <-- I've seen this method in Vue2 but in Vue3 the route.params is just empty here
}

I call this route:

<router-link :to="{ name: 'someRoute', params: { message: 'Some Message' } }">Some link</router-link>

When I change the path to path: '/someRoute/:message', the message is delivered fine, but I just want the message to be delivered without showing it in the url.

I've seen a few Vue2 examples using this approach (e.g. https://stackoverflow.com/a/50507329/1572330), but apparently they no longer work in Vue3.

Also have all the examples in the Vue3 documentation (https://github.com/vuejs/vue-router/blob/dev/examples/route-props/app.js / https://v3.router.vuejs. org/guide/essentials/passing-props.html) pass their value through the url itself, so I'm not sure if it's still possible.

Any ideas on this would be helpful.

P粉465675962
P粉465675962

reply all(1)
P粉431220279

Finally I found some relevant content in the change log: https://github.com/vuejs/router/blob/main/packages/router/CHANGELOG.md#414-2022-08-22

Obviously, it is no longer possible to send attributes via parameters without displaying them in the url. But luckily, they have some alternative suggestions. What worked best for my case was to use state: { ... } instead of:

<router-link :to="{ name: 'someRoute', force: true, state: { message: 'Some Message' } }">Some link</router-link>

Now, in the code of the page, I read the properties from history.sate and put that value into whatever properties I need.

If the url/route itself does not change, you need to have an update hook and use force: true

public created() {
    this.message = window.history.state.message;
}

public updated() {
    this.message = window.history.state.message;
}

PS history.state has some limitations, so in other cases one of the other suggestions in the changelog might be better

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!