Vue.js 通过路由器将不同的数据作为道具传递给子组件

时间:2021-03-11 18:39:48

标签: javascript vue.js vue-router vuejs3

我的 vue 应用中有一个嵌套路由器。

我的router/index.js

{
    path: "/parent",
    name: "Parent",
    component: () =>
      import(/* webpackChunkName: "parent" */ "../views/Parent.vue"),

    children: [{
      path: ':id',
      name: 'ChildOne',
      components: {
        nestedview: () =>
          import(/* webpackChunkName: "child-one" */ "../views/ChildOne.vue"),
      }
    },
    {
      path: "child-two",
      name: "ChildTwo",
      components: {
        nestedview: () =>
          import(/* webpackChunkName: "child-two" */ "../views/ChildTwo.vue"),
      }
    }]
  },

父组件模板(我使用 pug):

  router-view(
    name="nestedview",
    :functionOne="functionOne",
    :functionTwo="functionTwo",
    :functionThree="functionThree",
  )

问题是我只在 functionOne 组件中需要 functionTwofunctionThreeChildOne,我将它们作为道具传递。在 ChildTwo 组件中,我只需要作为 prop 传递的 functionOne,但在源代码的浏览器中,我可以看到另外两个以某种方式作为参数传递 functionTwo="function () { [native code] }" 和组件根元素的 functionThree="function () { [native code] }"

问题是,如果这些组件在技术上不是父组件的子组件,而是通过嵌套路由器呈现,是否有办法将不同的数据作为道具从父组件传递给子组件?

1 个答案:

答案 0 :(得分:1)

如果未找到属性,

v-bind 会自动绑定属性。

一个快速的解决方法是使用 v-bind.prop modifier,这样绑定只会在组件 prop 存在时才尝试设置它(否则,什么都没有绑定):

router-view(
  name="nestedview",
  :functionOne.prop="functionOne",
  :functionTwo.prop="functionTwo",
  :functionThree.prop="functionThree",
)

demo

相关问题