W
W
WebDev2017-08-16 21:07:35
Vue.js
WebDev, 2017-08-16 21:07:35

Should vue track data changes in the parent?

There is an application on the view, where there is a main object and components. All this works through vue-cli, that is, broken down into components.
I use the main view object as a repository of information that is convenient to use from all components.
It looks something like this:

new Vue({
...
data: {
    userInfo: {},
    messages: {},
    ...
}
});

As I understand it, vuex is used to store information, but I have not reached it yet.
So, from the components I access from like this:
this.$root.userInfo.name = 'Vasya';
this$root.messages.push({text: 'New message'});

And in one of the components, I display all messages directly from $root:
<li v-for="message in $root.messages">{{ message.text }}<li>

This code seemed to work, but for some reason it stopped responding to changes in $root.messages.
Instead, I set up a messages property in the component, and in the created method I assign messages from $root to it:
#mycomponent
data: function() {
    return {
        messages: []
    }
},
created: function() {
    this.messages = this.$root.messages
}

And when $root.messages changes, I emit an event that is caught in the same component. In general, if the component tracked changes from the main view object, then nothing would have to be done.
Is there something wrong with me, or is it supposed to be like this? And what do you do in such cases?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Anton, 2017-08-16
@kirill-93

need to use props and emit https://jsfiddle.net/eLu0zevg/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question