Updating parent data in Vue.js does not automatically trigger an update in the child component

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 could be causing this issue?

Answer №1

When a component is created, the data function is called only once in its life cycle. This means that the component will display the initial value at the time of creation.

It is considered poor practice to access data values from outside the component in Vue. Instead, follow the "props down, events up" principle and use properties within your component.

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

In this case, using a function to define Vue doesn't make much difference, but it is necessary for components to have their own isolated scope.

Check out this example for reference.

Answer №2

Only components require the callback function.


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

    // Defining a custom component in Vue
    Vue.component('custom-component', {
        data: function() {
            return {
                status: false
            }
        }
    });

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

FirebaseError encountered: Unable to update document due to absence of document. Updating document is only possible if document id is hard coded

For my latest project, I have a component that can successfully create a new user and add them to the database using the function createUserWithEmailAndPassword(auth, email, password). Now, I am working on another component that will allow users to edit t ...

How can I show a title when redirecting a URL in VUE JS?

My current setup includes a navigation drawer component that changes the title based on the user's route. For example, when navigating to the home page (e.g. "/"), the title updates to "Home", and when navigating to the profile page (e.g. /profile), t ...

Is it possible for a chrome extension to allow only specific third-party cookies and storage to be

My Chrome extension inserts an iframe from foo.com into bar.com, creating a situation where bar.com now includes a foo.com iframe. However, I have observed that this iframe encounters difficulties when attempting to write to localStorage if the user has ...

Updating Mapped Components with Selected State

One of the components in my project is a mapped component that dynamically displays API data. Each card displayed by this component receives unique props, resulting in cards that look different from one another. An example can be seen below. View Example ...

Implementing event handling with .On() in Jquery following .Off()

I need assistance with my responsive navigation bar. I am having trouble with the jQuery code to disable hover events if the width is less than or equal to 768px and enable it for desktop screens. $(window).on('load resize', function (e) { v ...

retrieve data from jsp page using ajax request

I've coded this JSP snippet Map<String, Long> map = new HashMap<String, Long>(); map.put("A", 10L); map.put("B", 20L); map.put("C", 30L); JSONObject json = new JSONObject(); json.accumulate ...

What is the best way to clear the selected option in a dropdown menu when choosing a new field element?

html <div class="row-fluid together"> <div class="span3"> <p> <label for="typeofmailerradio1" class="radio"><input type="radio" id="typeofmailerradio1" name="typeofmailerradio" value="Postcards" />Postcards& ...

Exploring locations using the Google Geolocation API

I have a website and am trying to determine the location of my visitors. I came across this code on Google Code: <script type="text/javascript" src="gears_init.js"></script> <script type="text/javascript"> var geo = google.gears.factory ...

The challenge with the Optional Chaining operator in Typescript 3.7@beta

When attempting to utilize the Typescript optional chaining operator, I encountered the following exception: index.ts:6:1 - error TS2779: The left-hand side of an assignment expression may not be an optional property access. Here is my sample code: const ...

Guide to successfully implement a POST action using jquery/ajax Colorbox! Check out the demo here

I stumbled upon a colorbox tutorial and attempted to replicate it with a POST action, but unfortunately, it just continues to load. Check out this fiddle The button represents the problematic POST action, while the text link is the original example that ...

Populate the content within a div element with specified height and width by utilizing JavaScript and jQuery

I need help with filling a fixed height div with long text retrieved via ajax in json format. For example, if I have a div with a height of 500px and width of 300px, with a font size of 16px. Is there a javascript recursive method that can fill the data ...

Issues with the Diagonal HTML Map functionality

I'm seeking assistance to implement a unique Google Maps Map on my webpage. I have a particular vision in mind - a diagonal map (as pictured below). My initial approach was to create a div, skew it with CSS, place the map inside, and then skew the ma ...

Deactivate a button when clicked on a card that has been mapped

After creating a card component and mapping through each card, I added an onClick function to disable the button of the clicked card. However, my logic ended up disabling all buttons instead. Here is the code snippet where I define the rendering of the UI ...

Tips on choosing JSON data to show on an HTML page

I am working with JSON data from a specific URL and I need to display only the information related to France on an HTML page. However, I am unsure of how to achieve this. Can someone please assist me? Here is my JavaScript code: // API Fetch Call const ...

Calculate the time difference in hours using time zone in Javascript

Within my JavaScript object, I have the following information: var dateobj = { date: "2020-12-21 03:31:06.000000", timezone: "Africa/Abidjan", timezone_type: 3 } var date = new Date(); var options = { timeZone: dateobj.timezone }; var curr_date ...

What causes the HTML element's X position value to double when its X position is updated after the drag release event in Angular's CDK drag-drop feature?

I am facing a challenge with an HTML element that has dual roles: Automatically moving to the positive x-level whenever an Obsarbalve emits a new value. Moving manually to both positive and negative x-levels by dragging and dropping it. The manual drag a ...

Guide on centering an unfamiliar element in the viewport using HTML, CSS, and JavaScript

In the process of developing my VueJS project, I have successfully implemented a series of cards on the page. However, I am now facing a challenge - when a user selects one of these cards, I want it to move to the center of the screen while maintaining its ...

How to use the sha512 hash function in Node.js for Angular2 and Ionic2 applications

I'm attempting to generate a SHA512 Hash in Angular2 (Ionic2) that matches the PHP function hash('sha512'). After trying out different modules like crypto-js, crypto, and js-sha512, I keep getting a different Hash compared to PHP. I even a ...

Verify if a specific key is present in associative arrays

Can you please explain the correct way to check for the existence of a key in associative arrays? For instance: var mydata = { key1: '', key2: { subkey1: { subkey1_1: { value1: '' ...

Storing each item in its own document within a Firebase collection

I have a feature where users input their sitemap and it generates all the links in the sitemap. How can I then store each of those links in separate documents within a specific collection on Firebase? Below is the current function used to set data in Fir ...