mismaah
mismaah

Reputation: 356

Pass object as prop when pushing route

This function is in a component outside router view.

goToMarkets(){
      this.$router.push({path: '/markets', params: {stock: this.model}})
    }

But the prop is undefined in the "Markets" component

Router:

const routes = [
  {
    path: '/markets',
    name: 'Markets',
    component: Markets,
    props: true
  },]

Markets component:

props: {
    stock: Object
  },

The prop is undefined in the Markets component even though it's not before it is passed (in the first function).

Upvotes: 2

Views: 4051

Answers (1)

Decade Moon
Decade Moon

Reputation: 34306

There's a couple of things happening here.

Firstly, route params form part of the URL and are defined upfront in the route definition.

Given the route definition:

{
  path: '/markets/:myparam',
  name: 'markets',
}

then you would transition to it like this:

this.$router.push({ name: 'markets', params: { myparam: 'foo' } })

and the URL would look like:

/markets/foo

You haven't defined any params for your route, so it won't work.

Secondly, the params must be strings or numbers. You can't pass objects as params. There is just no way to do this; it isn't supported. I think the philosophy here is that the URL alone should contain all router state.

One way to solve this is to pass an ID and then fetch the object from the ID from some shared store (e.g. Vuex).

I don't know what your stock model is, but perhaps the param could be just a string like msft so the URL is like /markets/msft? Can you make it work without needing to pass the full object?

If it's a small object, you can deconstruct the properties of the object into query parameters. But you cannot pass an object instance along with the route transition like you would pass an object as an argument to a function call.

Upvotes: 7

Related Questions