How To Share Data Between Components In Vue Js (while Creating List)
Solution 1:
The whole point of having a great MVVM framework is to let you have a view-model: a central store of all the state in your page/app/whatever. Components can emit events. You can have an event bus. But if you can save the day with a simple, global variable containing all your state, this is by far the cleanest, best solution. So just put your to-dos in an array, in a variable in global scope, then declare them in the data
of every component that needs them. Here it is working in Plunkr.
markup
<divid="App" ><add-todo></add-todo><my-component></my-component></div><templateid="add-todo"><div><inputtype="text"v-model="message"><button @click="addTodo">Add todo</button></div></template><templateid="todo-template"><div><ul ><liv-for="(item,index) in store.items">
{{item.message}}
</li></ul></div></template><scriptsrc="vue.js"></script><scriptsrc="script.js"></script>
code
// This is the magic store. This is all you need.var vueStore = {items : []};
varMyComponent = Vue.extend({
template: '#todo-template',
data : function(){return {store : vueStore}}
});
varAddTODO = 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 = newVue({
el: '#App',
data: {
store : vueStore
},
});
This is not a savage hack! We're being called to stop thinking about events, move up the food chain, and think about reactive pipes. Components don't care when or by who the central store gets updated. Vue takes care of it.
Here's the page on state management.
Solution 2:
So you could use events and emit the created todo to the root vue instance. I edited / forked your plunkr (I'm rather the fiddle type).
https://plnkr.co/edit/bnMiDmi30vsj3a8uROBK?p=preview
So I edited this line here, which listens for a custom event added
and pushes the first argument to items.
<add-todo v-on:added='items.push(arguments[0])'></add-todo>
And also these lines, which emit the event. And i changed from the property m
to the data message
, because you shouldnt mutate props:
<input type="text" v-model="message">
<button @click="$emit('added', message)">Add todo</button>
Post a Comment for "How To Share Data Between Components In Vue Js (while Creating List)"