Nuxt pass props programmatically, through router

Viewed 1977

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/

4 Answers

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

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.

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

Related