gpt4 book ai didi

javascript - Vue Router 将 Prop 传递给动态加载的 child

转载 作者:行者123 更新时间:2023-11-29 10:58:56 25 4
gpt4 key购买 nike

我正在学习 Vue atm,我无法通过 Vue 路由在子组件和父组件之间传递 Prop 。我有一个布局组件,它有一个包装器 DIV,看起来像这样:

<template>
<div class="container" v-bind:class="cssClass">
<router-view></router-view>
</div>
</template>

<script>
export default {
name: 'Layout',
props: ['cssClass']
}
</script>

我已经在我的基础 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: '' } }
]
},
]
});

但是,一旦我点击了/hello-world 路线,我想将一个空的 cssClass Prop 传递给 Layout,(HelloWorldPage 当前嵌套在其中)——我该怎么做呢? Prop 甚至是实现这一目标的机制吗?

最佳答案

我想通了,这是否是解决我的问题的最佳解决方案是任何人的猜测。

在 Vue 路由器上传递时,子 props 似乎不会被父级自动拾取。因此,一旦组件被动态构建/注入(inject),它们都会调用我的自定义 childinit 事件,该事件会发回父级(布局)中定义的路由器 View 。我将父级中的局部变量设置为发出的子级的值,然后将类绑定(bind)到它。

const router = new VueRouter({
routes: [
{
path: '/',
component: Layout,
children: [
{
path: '',
component: Homepage,
props: { cssClass: 'home' },
},
{
path: '/helloworld',
component: HelloWorldPage,
props: { cssClass: 'helloworld' }
}
]
}
]
});

我的布局组件:

<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>

我的主页组件:

export default {
name: 'Homepage',
props: ['cssClass'],
created() {
this.$emit('childinit', this.cssClass);
}
}

HelloWorld 组件也会发出,创建的方法可能不需要复制;可能会尝试看看您是否可以扩展一个基本组件,该组件将始终在两个组件的 init 上发出。

关于javascript - Vue Router 将 Prop 传递给动态加载的 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51140952/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com