Vue 从子组件向子组件传递数据
Vue pass data from child component to child component
所以我有这样的结构
<Root>
<HomeNav> router-view
<RouterLink>
<RouterLink>
<RouterLink>
<RouterLink>
<RouterLink>
<Home> router-view
<RouterLink>
现在,每个 HomeNav 路由器链接都通过将数据传递给根来更改组件中的数据,但这意味着我需要绑定该数据:
<router-view v-bind:title="title" v-bind:text="text" v-bind:youtube="youtube" v-bind:transition="transition"></router-view>
和运行 创建和更新的函数:
new Vue({
el: '#app',
router,
data: Variables,
created: function () {
path = pathname.pathname();
pathLenght = pathname.countPathLenght(path);
this.homeText(this.data);
},
updated: function () {
path = pathname.pathname();
pathLenght = pathname.countPathLenght(path);
Pace.restart()
this.homeText(this.data);
},
methods: {
homeText(data) {
data = toogleData.checkText(data);
this.title = data[0];
this.text = data[1];
this.youtube = data[2];
}
}
})
但是,问题是我不需要所有路由上的数据,也不需要触发 this.homeText 函数或在每个根上绑定特定数据。只有首页需要,所以第一个路由。
所以问题是,是否可以直接将数据从 HomeNav 组件传递到 Home 组件,而无需将所有代码都放在全局(根)组件中?
这是 VueJs 文档建议的 MessagePump 的好地方。它本质上是未绑定的 Vue 对象,充当对象之间的中介。这允许您定义和调用泵上的事件,这些事件将传递给适当的组件。
window.MessagePump = new Vue({});
Vue.Component(
'HomeNav',
{
...
data: function () {
return {
homeText: 'something'
}
},
...
mounted: function () {
var thisArg = this
MessagePump.$on(
'homeTextChanged',
function(newText) {
thisArg.homeText = newText;
}
);
}
...
}
);
Vue.Component(
'Home',
{
...
mounted: function () {
MessagePump.$emit('homeTextChanged', 'To This');
}
...
}
);
这将触发事件并将 homeText 从 'something' 更改为 'To This'。
所以我有这样的结构
<Root>
<HomeNav> router-view
<RouterLink>
<RouterLink>
<RouterLink>
<RouterLink>
<RouterLink>
<Home> router-view
<RouterLink>
现在,每个 HomeNav 路由器链接都通过将数据传递给根来更改组件中的数据,但这意味着我需要绑定该数据:
<router-view v-bind:title="title" v-bind:text="text" v-bind:youtube="youtube" v-bind:transition="transition"></router-view>
和运行 创建和更新的函数:
new Vue({
el: '#app',
router,
data: Variables,
created: function () {
path = pathname.pathname();
pathLenght = pathname.countPathLenght(path);
this.homeText(this.data);
},
updated: function () {
path = pathname.pathname();
pathLenght = pathname.countPathLenght(path);
Pace.restart()
this.homeText(this.data);
},
methods: {
homeText(data) {
data = toogleData.checkText(data);
this.title = data[0];
this.text = data[1];
this.youtube = data[2];
}
}
})
但是,问题是我不需要所有路由上的数据,也不需要触发 this.homeText 函数或在每个根上绑定特定数据。只有首页需要,所以第一个路由。
所以问题是,是否可以直接将数据从 HomeNav 组件传递到 Home 组件,而无需将所有代码都放在全局(根)组件中?
这是 VueJs 文档建议的 MessagePump 的好地方。它本质上是未绑定的 Vue 对象,充当对象之间的中介。这允许您定义和调用泵上的事件,这些事件将传递给适当的组件。
window.MessagePump = new Vue({});
Vue.Component(
'HomeNav',
{
...
data: function () {
return {
homeText: 'something'
}
},
...
mounted: function () {
var thisArg = this
MessagePump.$on(
'homeTextChanged',
function(newText) {
thisArg.homeText = newText;
}
);
}
...
}
);
Vue.Component(
'Home',
{
...
mounted: function () {
MessagePump.$emit('homeTextChanged', 'To This');
}
...
}
);
这将触发事件并将 homeText 从 'something' 更改为 'To This'。