简体   繁体   中英

Parent's data change does not update child component in vuejs

I have the following:

Vue.component('times-updated', {
    template: '<span>Times Updated: {{ timesUpdated }}</span>',
    data: function() {
        return {
            timesUpdated: this.$parent.myData.timesUpdated
        }
    }
});


var vm = new Vue({
    el: '#test',
    data: function() {
        return {
            myData: {}
        }
    }
})

setInterval(function(){
    $.ajax({
        url: `${window.location.href}/json`, // This just returns an array : array.timesUpdated: 2 etc
    }).done(function (data) {
        vm.myData = data; // changes this data
    });
}, 1000)

and am using the following html:

<div class="test">  
    <times-updated></times-updated>
</div>

I poll a REST API that returns an array which includes a timesUpdated property:

{
    timesUpdated: 5
}

My intention is that every second I use jQuery's $.ajax method to call the API, update the myData data object on vm , which would then update the times-updated component.

The code works on initial page load, the times-updated component can retrieve the value on its parent's myData property, but whilst I have confirms that vm.myData does reflect the new value from the API, the component doesn't update its display to show the new count.

What am i doing wrong?

The data function is only called once during the life cycle of the component; when it is initially created. So essentially your component is just displaying the value as it existed when the component was created.

Additionally, it's generally bad practice to reach out of a component to get a data value. Vue is props down, events up . You should convert your component to use a property.

Vue.component('times-updated', {
  props:["times"],
  template: '<span>Times Updated: {{ times }}</span>',
})

The fact that you are using a function to define the Vue in this particular case doesn't really matter, it's just not a typical practice. Components require a function because they need an isolated scope.

Here is an example .

That callback is required only in components

    // vue instance
    new Vue({
        data: {
            status: true
        }
    };

    // vue components (callback)
    Vue.component('custom-component', {
        data: function() {
            return {
                status: false
            }
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM