[英]How I Can Change The Another Component Data on VueJS
I have a classic Vue Component like this我有一个像这样的经典 Vue 组件
Vue.component('bar', {
template: `<div class="bar"></div>`,
data () {
return {
blocks: [
]
}
}
});
And also i have Vue Instance like this.而且我也有这样的 Vue 实例。
new Vue ({
el: '#app',
data: {
value: 1
},
methods: {
add: function() {
// here to do
}
}
});
When add function work, i have to add to data component blocks value.添加功能工作时,我必须添加数据组件块值。 I can't use Vuex and what is this other solutions?
我不能使用 Vuex,其他解决方案是什么?
You can use the way which called “Event bus”您可以使用称为“事件总线”的方式
https://alligator.io/vuejs/global-event-bus/ https://alligator.io/vuejs/global-event-bus/
Or you can create your own state management或者您可以创建自己的状态管理
https://v2.vuejs.org/v2/guide/state-management.html#Simple-State-Management-from-Scratch https://v2.vuejs.org/v2/guide/state-management.html#Simple-State-Management-from-Scratch
But i highly recommend you too use vuex, since it will become hard to manage events and state when the project grows但我强烈建议你也使用 vuex,因为随着项目的增长,管理事件和状态会变得很困难
Since this is a parent -> child communication, you can very simply use props:由于这是一个父 -> 子通信,您可以非常简单地使用道具:
blocks
on the parent component.blocks
。blocks
as a prop to bar
component.blocks
作为道具传递给bar
组件。 Here's some guiding:这里有一些指导:
Define your component with props:用 props 定义你的组件:
Vue.component('bar', { template: `<div class="bar">{{blocks.length}}</div>`, props: ['blocks'] });
Define blocks
on the parent (in your example, the main vue component):在父级上定义
blocks
(在您的示例中,主 vue 组件):
new Vue ({ el: '#app', data: { blocks: [] }, methods: { add: function() { // do something with blocks } } });
Pass data down to the component:将数据向下传递给组件:
<bar :blocks="blocks"></bar>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.