【问题标题】:Vue router passing props is undefinedVue路由器传递道具未定义
【发布时间】:2021-09-11 21:00:15
【问题描述】:

我想通过 vue 路由器传递一个道具,路由器链接看起来像这样

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

这是我的路线

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

我已将 props 设置为 true,并将参数添加到路径 /:productId。我也按照这个链接的例子 https://codesandbox.io/s/o41j762pnz

我正在尝试将该道具传递给我的组件,但是当我想在我的组件中使用该道具时,道具总是未定义。 这是我的组件

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

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

我完全喜欢这个例子,这个例子运行完美,没有任何问题,但我的没有。我该如何解决?

谢谢

【问题讨论】:

  • 你能告诉我们你的 CodeSandbox 在哪里不起作用吗?
  • @IVOGELOV 很抱歉让您久等了,这是链接codesandbox.io/s/unruffled-galileo-0m959?file=/src/main.js 请忽略乱码,因为我没有加载css,如果您查看控制台,它会显示未定义
  • 对于具有命名视图的路由,您需要为要将参数传递到的每个单独视图定义道具:router.vuejs.org/guide/essentials/…
  • @Terry 我照你说的做了,还是一样未定义,我做了类似的事情{ path: '/product/details', name: 'product-details', props: { productId: Number }, components: { navbar: Navbar, default: ProductDetail, footer: Footer }, },
  • @Villian 你做错了。参考我的回答。

标签: javascript vue.js vue-router


【解决方案1】:

当您使用named views in your router 时,您不能只声明prop: true。您必须在要接收参数的每个视图上明确声明。这可以通过更改prop 的定义方式来完成。这就是你现在的做法,这不会起作用:

props: true

正确方法:

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

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

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
    }
  }
];

【讨论】:

    猜你喜欢
    • 2021-08-21
    • 2019-07-31
    • 2019-03-23
    • 2018-11-04
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 2020-04-03
    相关资源
    最近更新 更多