简体   繁体   中英

How to pass data to vue router router-view?

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

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 :

编辑 Vue 模板

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.

我个人决定使用提供/注入功能:以最小的开销保持反应性。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM