Vue 路由器传递 props 未定义

Vil*_*ian 1 javascript vue.js vue-router

我想通过 vue 路由器传递道具,路由器链接如下所示

<router-link :to="{ name: 'product-details', params: { productId: 123 } }" class="product-sbb d-block">
Run Code Online (Sandbox Code Playgroud)

这是我的路线

{
  path: '/product/details/:productId',
  name: 'product-details',
  props: true,
  components: {
   navbar: Navbar,
   default: ProductDetail,
   footer: Footer
 },
},
Run Code Online (Sandbox Code Playgroud)

我已将 props 设置为 true 并将参数添加到路径/:productId。我还按照此链接中的示例进行操作 https://codesandbox.io/s/o41j762pnz

我试图将该道具传递给我的组件,但是当我想在组件中使用该道具时,道具始终为undefined。这是我的组件

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

export default {
  props: {
    productId: Number
  },
  data() {
  },
  created() {
    console.log(this.productId)
  }
}
Run Code Online (Sandbox Code Playgroud)

我的做法与该示例完全相同,该示例运行完美,没有任何问题,但我的却没有。我该如何解决这个问题?

谢谢

Ter*_*rry 7

当您在路由器中使用命名视图时,您不能只声明prop: true。您必须在要接收参数的每个视图上显式声明。prop这可以通过更改定义方式来完成。这就是你现在所做的,这是行不通的:

props: true
Run Code Online (Sandbox Code Playgroud)

正确的做法:

props: {
    // You must set `true` to the default view, which uses ProductDetail
    default: true
}
Run Code Online (Sandbox Code Playgroud)

所以你的路线应该是这样的:

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
    }
  }
];
Run Code Online (Sandbox Code Playgroud)