简体   繁体   中英

Vue router passing props is undefined

I want to pass a props via the vue router with the router link looks like this

<router-link :to="{ name: 'product-details', params: { productId: 123 } }" class="product-sbb d-block">

And this is my routes

{
  path: '/product/details/:productId',
  name: 'product-details',
  props: true,
  components: {
   navbar: Navbar,
   default: ProductDetail,
   footer: Footer
 },
},

I have set the props to true and also add the params to the path /:productId . I also follow the example from this link https://codesandbox.io/s/o41j762pnz

I'm trying to pass that props to my component, but when I want to use that props in my component, the props always undefined . Here's my component

import ProductDetail from '../components/parts/ProductDetailGallery.vue';

export default {
  props: {
    productId: Number
  },
  data() {
  },
  created() {
    console.log(this.productId)
  }
}

I did exactly like the example, the example run perfect without any issue, but mine didn't. How do I solve this?

Thank you

As you are using named views in your router , you cannot just declare prop: true . You will have to declare that explicitly on each view that you want to receive the parameter. This can be done by changing how prop is defined. This is how you're doing it now, which will not work:

props: true

The correct way:

props: {
    // You must set `true` to the default view, which uses ProductDetail
    default: true
}

So your routes should look like this:

const routes = [
  {
    path: "/product/details/:productId",
    name: "product-details",
    components: {
      navbar: Navbar,
      default: ProductDetail,
      footer: Footer
    },
    props: {
      // You must set `true` to the default view, which uses ProductDetail
      default: true
    }
  }
];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM