将道具传递给由 Vue-router 实例化的 Vue.js 组件

假设我有这样一个 Vue.js 组件:

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

当 Vue-router 中的某个路由被匹配时,我想使用它:

router.map({
'/bar': {
component: Bar
}
});

通常,为了将‘ myProps’传递给组件,我会这样做:

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

以及 html:

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

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

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

110091 次浏览
<router-view :some-value-to-pass="localValue"></router-view>

在你的组件中加入道具:

props: {
someValueToPass: String
},

视频路由器将匹配支撑组件

 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 } }
]
})

这是官方的回答。 链接

在路由器里,

const router = new VueRouter({
routes: [
{ path: 'YOUR__PATH', component: Bar, props: { authorName: 'Robert' } }
]
})

<Bar />组件内部,

var Bar = Vue.extend({
props: ['authorName'],
template: '<p>Hey, \{\{ authorName }}</p>'
});

遗憾的是,以前的解决方案实际上都没有回答这个问题,所以这里有一个来自 Quora的解决方案

基本上 医生没有解释清楚的部分是

当道具设置为 true 时,route.params将被设置为组件道具。

所以当你通过路线发送道具时,你实际上需要的是把它分配给 params键 ex

this.$router.push({
name: 'Home',
params: {
theme: 'dark'
}
})

所以完整的例子就是

// component
const User = {
props: ['test'],
template: '<div>User \{\{ test }}</div>'
}


// router
new VueRouter({
routes: [
{
path: '/user',
component: User,
name: 'user',
props: true
}
]
})


// usage
this.$router.push({
name: 'user',
params: {
test: 'hello there' // or anything you want
}
})

用途:

this.$route.MY_PROP

找个道具

这个问题是旧的,所以我不知道如果 功能模式存在的时候,这个问题被问,但它可以用来只通过正确的道具。它只在路由更改时调用,但是如果已经是反应性数据,则所有 Vue 反应性规则都适用于您传递的任何数据。

// Router config:
components: {
default: Component0,
named1: Component1
},
props: {
default: (route) => {
// <router-view :prop1="$store.importantCollection"/>
return {
prop1: store.importantCollection
}
},
named1: function(route) {
// <router-view :anotherProp="$store.otherData"/>
return {
anotherProp: store.otherData
}
},
}

请注意,这只有当您的道具函数的作用域设定为可以看到您想要传递的数据时才有效。route参数不提供对 Vue 实例、 Vuex 或 VueRouter 的引用。此外,named1示例还演示了 this也不绑定到任何实例。这似乎是设计好的,因此状态只由 URL 定义。由于这些问题,最好使用在标记中接收正确道具的命名视图,并让路由器切换它们。

// Router config:
components:
{
default: Component0,
named1: Component1
}
<!-- Markup -->
<router-view name="default" :prop1="$store.importantCollection"/>
<router-view name="named1" :anotherProp="$store.otherData"/>

使用这种方法,您的标记声明哪些视图是可能的并设置它们,但是路由器决定激活哪些视图。