您能否告诉我如何在 VUE js 中的组件之间共享数据(创建列表时)。我有两个组件 list components
和 add todo component
.当用户点击 add button
时,我想在列表中添加项目.但是问题是输入字段存在于不同的组件中,而列表存在于不同的组件中
这是我的代码
https://plnkr.co/edit/bjsVWU6lrWdp2a2CjamQ?p=preview
//代码在这里
var MyComponent = Vue.extend({
template: '#todo-template',
props: ['items']
});
var AddTODO = Vue.extend({
template: '#add-todo',
props: ['m'],
data: function () {
return {
message: ''
}
},
methods: {
addTodo: function () {
console.log(this.message)
console.log(this.m);
//this.m =this.message;
},
},
});
Vue.component('my-component', MyComponent);
Vue.component('add-todo', AddTODO)
var app = new Vue({
el: '#App',
data: {
message: '',
items: []
},
});
最佳答案
拥有一个出色的 MVVM 框架的全部意义在于让您拥有一个 View 模型:页面/应用程序/任何内容中所有状态的中央存储。组件可以发出事件。你可以有一个事件总线。 但是如果您可以使用包含所有状态的简单全局变量来节省时间,那么这是迄今为止最干净、最好的解决方案。因此,只需将您的待办事项放在一个数组中,放在一个全局范围的变量中,然后在 data
中声明它们。需要它们的每个组件。 Here it is working in Plunkr .
标记
<div id="App" >
<add-todo></add-todo>
<my-component></my-component>
</div>
<template id="add-todo">
<div>
<input type="text" v-model="message">
<button @click="addTodo">Add todo</button>
</div>
</template>
<template id="todo-template">
<div>
<ul >
<li v-for="(item,index) in store.items">
{{item.message}}
</li>
</ul>
</div>
</template>
<script src="vue.js"></script>
<script src="script.js"></script>
代码
// This is the magic store. This is all you need.
var vueStore = {items : []};
var MyComponent = Vue.extend({
template: '#todo-template',
data : function(){return {store : vueStore}}
});
var AddTODO = Vue.extend({
template: '#add-todo',
data: function () {
return {
message: '',
store : vueStore
}
},
methods: {
addTodo: function (event) {
this.store.items.push({'message' : this.message})
},
},
});
Vue.component('my-component', MyComponent);
Vue.component('add-todo', AddTODO)
var app = new Vue({
el: '#App',
data: {
store : vueStore
},
});
这不是野蛮的黑客攻击!我们被要求停止思考事件,向上移动食物链,并考虑 react 管道。组件不关心中央存储何时或由谁更新。 Vue 会处理它。
Here's状态管理页面。
关于javascript - 如何在 VUE js 中的组件之间共享数据(创建列表时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46015442/