3

Im using Vue Router. In my code I used to have:

<div v-bind:is="page.component_name" v-bind:page="page"></div>

Which worked, and the page data was passed to the component. But how do I do the same with a router-view? This doesn't seem to work:

<router-view v-bind:page="page"></router-view>

js:

var vm = new Vue({
    ...,
    router : new VueRouter({
        routes : [
            { path: '/foo', component: { template: '<div>foo</div>', created:function(){alert(1);} } },
            //{ path: '/bar', component: { template: '<div>bar</div>', created:function(){alert(2);} } },
            { path: '/bar', component: Vue.component("ti-page-report") }
        ]
    }),
     ...
});

3 Answers 3

2

vue-router has a dedicated page in docs on how to pass props to router-view.

Passing Props to Route Components

Example snippet from docs:

const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User, props: true },

     // for routes with named views, you have to define the `props` option for each named view:
    {
      path: '/user/:id',
      components: { default: User, sidebar: Sidebar },
      props: { default: true, sidebar: false }
    }
  ]
})

If you are looking for simplified usage, props can still be passed the same way they are passed to any component. But component that is used for rendering the route (the one that is specified in route definition) should expect to receive the props.

Here is simple usage example of passing props to router-view:

Edit Vue Template

Sign up to request clarification or add additional context in comments.

6 Comments

How would I set it up, so I can access page.icon for example in the component?
The example code is confusing as it doesn't show how to access the prop values from the component.
I've added simplified usage example to the answer. Please, check the way title prop is passed to <router-view>. Does this help your issue?
In my case, the :title="...", the ... is a function which gets the right data based on a click event that needs to happen first, however the router "to" happens before and then I get a bunch of console errors about undefined values.
nvm i solved it with this github.com/vuejs/vue-router/issues/800
|
1

I personally decided to use provide/inject feature: preserving reactivity with minimal overhead.

1 Comment

Please add some further information on how you would solve it using the technique you mention.
0

The component ("ti-page-report") that needs to access the props being sent just needs to add it:

<template>
  <div>
    <h1>Now you can access page: {{ page }}</h1>
  </div>
</template>

export default {
  name: "TiPageReport",
  props: ['page'], // can now be accessed with this.page
  ...
};

See https://v2.vuejs.org/v2/guide/components-props.html for how to use props properly.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.