Pass object as prop when pushing route

南笙酒味 提交于 2021-01-28 06:16:37

问题


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

The whole code: https://github.com/mismaah-abdulla/stock-portfolio/tree/master/src


回答1:


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.



来源:https://stackoverflow.com/questions/60770633/pass-object-as-prop-when-pushing-route

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!