Rob*_*ert 40 vue.js vue-router
假设我有一个像这样的Vue.js组件:
var Bar = Vue.extend({
props: ['my-props'],
template: '<p>This is bar!</p>'
});
Run Code Online (Sandbox Code Playgroud)
我希望在vue-router中的某些路由匹配时使用它:
router.map({
'/bar': {
component: Bar
}
});
Run Code Online (Sandbox Code Playgroud)
通常,为了将'myProps'传递给组件,我会做这样的事情:
Vue.component('my-bar', Bar);
Run Code Online (Sandbox Code Playgroud)
并在HTML中:
<my-bar my-props="hello!"></my-bar>
Run Code Online (Sandbox Code Playgroud)
在这种情况下,路由器在路由匹配时自动绘制路由器视图元素中的组件.
我的问题是,在这种情况下,我如何将道具传递给组件?
luk*_*pep 61
<router-view :some-value-to-pass="localValue"></router-view>
Run Code Online (Sandbox Code Playgroud)
并在您的组件中添加prop:
props: {
someValueToPass: String
},
Run Code Online (Sandbox Code Playgroud)
vue-router将匹配组件中的prop
ctf*_*tf0 11
不幸的是,没有上一个解决方案实际上回答了这个问题,所以这里是一个来自quora的问题。
基本上,文档不能很好解释的部分是
当props设置为true时,
route.params将会被设置为组件props。
因此,通过路线发送道具时,您真正需要的是将其分配给params钥匙ex
this.$router.push({
name: 'Home',
params: {
theme: 'dark'
}
})
Run Code Online (Sandbox Code Playgroud)
所以完整的例子是
// 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
}
})
Run Code Online (Sandbox Code Playgroud)
在路由器中
const router = new VueRouter({
routes: [
{ path: 'YOUR__PATH', component: Bar, props: { authorName: 'Robert' } }
]
})
Run Code Online (Sandbox Code Playgroud)
在<Bar />组件内部
var Bar = Vue.extend({
props: ['authorName'],
template: '<p>Hey, {{ authorName }}</p>'
});
Run Code Online (Sandbox Code Playgroud)
这个问题很旧,所以我不确定在提出问题时是否存在函数模式,但它可以用于仅传递正确的道具。它仅在路线更改时被调用,但所有 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
}
},
}
Run Code Online (Sandbox Code Playgroud)
请注意,这仅在您的 prop 函数具有作用域时才有效,因此它可以看到您想要传递的数据。该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"/>
Run Code Online (Sandbox Code Playgroud)
使用这种方法,您的标记声明哪些视图是可能的并设置它们,但路由器决定激活哪些视图。
| 归档时间: |
|
| 查看次数: |
42116 次 |
| 最近记录: |