2016-06-21 138 views
16

假设实例化的组件Vue.js我有一个Vue.js成分是这样的:传递道具由Vue的路由器

var Bar = Vue.extend({ 
    props: ['my-props'], 
    template: '<p>This is bar!</p>' 
}); 

而且我想用它当VUE路由器的一些路线这样的匹配:

router.map({ 
    '/bar': { 
     component: Bar 
    } 
}); 
为了通过 'myProps' 的成分,我会做这样的事情

通常情况下:

Vue.component('my-bar', Bar); 

,并在T他html:

<my-bar my-props="hello!"></my-bar> 

在这种情况下,当路由匹配时,路由器自动绘制router-view元素中的组件。

我的问题是,在这种情况下,我如何将道具传递给组件?

回答

25
<router-view :some-value-to-pass="localValue"></router-view> 

,并在你的组件只需添加道具:

props: { 
     someValueToPass: String 
    }, 

VUE路由器将组件匹配道具

+0

另外'道具: “为prop1”, “PROP2”, “prop3”]'更可以在这里找到http://vuejs.org/guide/components.html#Props – dlkulp

+0

@lukpep我已经运行当我将我的道具绑定在''上时,我收到以下错误“Attribute”:my_prop“在组件上被忽略,因为该组件是一个片段实例。任何想法有什么不对? – highFlyingDodo

+0

这可能是一个坏主意。当用户通过URL直接发送时会发生什么? – shakee93

4
const User = { 
     props: ['id'], 
     template: '<div>User {{ id }}</div>' 
    } 
    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 } 
     } 
     ] 
    }) 

对象模式

const router = new VueRouter({ 
    routes: [ 
    { path: '/promotion/from-newsletter', component: Promotion, props: { newsletterPopup: false } } 
    ] 
}) 

这是官方回答。 link

+5

在这种情况下,人们会在哪里实际传递字符串“hello”,如问? – mcheah

+0

在官方文档中进一步阅读:“当道具设置为true时,route.params将被设置为组件道具。”作者问如何设置自定义值“hello” – tgf