mikebrsv
mikebrsv

Reputation: 1960

Vue.js passing different data as props to child components via router

I have a nested router in my vue app.

My 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"),
      }
    }]
  },

Parent component template (I use pug):

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

The thing is that I need functionOne, functionTwo and functionThree only in the ChildOne component, where I pass them as props. In the ChildTwo component I need only the functionOne which I pass as a prop, but in my browser in the source code I can see that the other two are somehow passed as parameters functionTwo="function () { [native code] }" and functionThree="function () { [native code] }" of the root element of the component.

The question is, is there a way to pass from the Parent component to the Child components different data as props if these components are technically not child components of the Parent, but are rendered via the nested router?

Upvotes: 0

Views: 621

Answers (1)

tony19
tony19

Reputation: 138226

v-bind automatically binds an attribute if a property is not found.

A quick fix is to use v-bind's .prop modifier so that the binding only tries to set the component prop if it exists (otherwise, nothing is bound):

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

demo

Upvotes: 1

Related Questions