Squ*_*gs. 6 javascript vue.js vue-router vuejs2
我正在学习 Vue atm,但我无法通过 Vue Routes 在子组件和父组件之间传递道具。我有一个 Layout 组件,它有一个包装 DIV,如下所示:
<template>
<div class="container" v-bind:class="cssClass">
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'Layout',
props: ['cssClass']
}
</script>
Run Code Online (Sandbox Code Playgroud)
我在我的基本 App JS 中定义了我的路线,如下所示。所以我对第一次加载的看法是“容器动画”类,一切都很好。
const router = new VueRouter({
routes: [
{ path: '/', component: Layout, props: { cssClass: 'container-animated' },
children: [
{ path: '', component: Homepage },
{ path: '/hello-world', component: HelloWorldPage, props: { cssClass: '' } }
]
},
]
});
Run Code Online (Sandbox Code Playgroud)
但是,一旦我点击 /hello-world 路线,我想将一个空的 cssClass 道具传递给 Layout,(HelloWorldPage 当前嵌套在其中) - 我该怎么做?道具甚至是实现这一目标的机制吗?
我想通了,这是否是我的问题的最佳解决方案是任何人的猜测。
看起来子 props 在 Vue Router 上传递时不会被父级自动拾取。因此,一旦动态构建/注入组件,它们都会调用我的自定义 childinit 事件,该事件会发送回父级(布局)中定义的路由器视图。我将父级中的局部变量设置为发出的子级的值,然后将类绑定到它。
const router = new VueRouter({
routes: [
{
path: '/',
component: Layout,
children: [
{
path: '',
component: Homepage,
props: { cssClass: 'home' },
},
{
path: '/helloworld',
component: HelloWorldPage,
props: { cssClass: 'helloworld' }
}
]
}
]
});
Run Code Online (Sandbox Code Playgroud)
我的布局组件:
<template>
<div class="container" v-bind:class="className">
<router-view v-on:childinit="onChildInit"></router-view>
</div>
</template>
<script>
export default {
name: 'Layout',
props: ['cssClass'],
data() {
return {
className : ''
}
},
methods: {
onChildInit( value ){
this.className = value;
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
我的主页组件:
export default {
name: 'Homepage',
props: ['cssClass'],
created() {
this.$emit('childinit', this.cssClass);
}
}
Run Code Online (Sandbox Code Playgroud)
HelloWorld 组件也会发出,可能不需要复制创建的方法;可能会尝试看看是否可以扩展一个基本组件,该组件将始终在两个组件的 init 上发出。
| 归档时间: |
|
| 查看次数: |
6812 次 |
| 最近记录: |