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

Express.js returning unexpected results when calling MySQL stored procedures

I've encountered a strange issue with a stored procedure called getUsers in MYSQL. When I execute the procedure in phpmyadmin, it returns a table of users with their data perfectly fine. However, when I try to call the same procedure from my Node.js a ...

How can I verify if a user is logged in using express.Router middleware?

Is there a way to incorporate the isLoggedIn function as a condition in a get request using router.route? const controller = require('./controller'); const Router = require('express').Router; const router = new Router(); function isLo ...

Axios is causing my Pokemon state elements to render in a jumbled order

Forgive me if this sounds like a silly question - I am currently working on a small Pokedex application using React and TypeScript. I'm facing an issue where after the initial page load, some items appear out of order after a few refreshes. This make ...

Monitor modifications to an <input type="text"> element as its value is updated dynamically through JQuery from the server side

I am struggling with detecting when the value of an input field changes after it has been set by clicking a button. I have tried various events but can't seem to find the right one. <!DOCTYPE html> <html> <head> <script src=" ...

How can dynamic values be displayed in VueJS?

I'm looking to display dynamic titles based on the number of times a value is added. For example, if a user selects cats and clicks Add, I want the title to show as cats 1. If the user adds it again, then it should be displayed as cats 2, and so on fo ...

The error you are seeing is a result of your application code and not generated by Cypress

I attempted to test the following simple code snippet: type Website = string; it('loads examples', () => { const website: Website = 'https://www.ebay.com/'; cy.visit(website); cy.get('input[type="text"]').type(& ...

Wrap the chosen text within tags in a particular element

Is there a way to wrap <span> tags around selected text within an element? For instance, if someone highlights the word "John", I would like to enclose it with span tags. Sample Code in HTML <p>My name is Jimmy John, and I hate sandwiches. M ...

Running a designated AJAX function from a variable by utilizing Applescript

Struggling to execute a JavaScript code within a page using Applescript. In the JavaScript, an AJAX function was defined like so: var myFunction = function () { // Here be the code... } I attempted this in Applescript: do JavaScript "document.myFunct ...

The Element Ui component fails to update when the prop of the Vue component changes

In my project, I have a parent component and several child components which all make use of the same prop. This prop is an array of keys that are used for a dropdown menu in element.js. Initially, when the children render for the first time, they do not co ...

Guide to importing a Kotlin/JS generated module into a separate npm-dependent project

I am interested in developing a JavaScript library using Kotlin Multiplatform (such as the project found here, which includes a websocket server and a JavaScript client). My goal is to build this library as an npm package and then import it into my Vue pro ...

Using data from an API, I am implementing JavaScript validation for my dropdown select menu

Using an API, I am able to access information about the city's subway stations through a select option. Currently, I can only display details about one station (Balard). However, I would like to be able to display information about other stations tha ...

Extracting the href attribute from a child <a> tag

I am struggling to retrieve the value of the href within the code structure below: <div class=""> <div class=""> <div class=""> <a href=""><img src=""></a> </div> </div> </div> The m ...

Guide to creating animations with javascript/react js

My attempt at altering the opacity of an element every 100 milliseconds following a click event has not been successful. The function change is triggered by a click, yet the code does not work as intended. Here's what I have so far: function change (i ...

retrieving the outcome from a PHP script invoked through Ajax

Having trouble transferring the results of a PHP script to HTML input fields This is my PHP script: $stmt->execute(); if ($stmt->rowCount() > 0){ $row = $stmt->fetch(PDO::FETCH_ASSOC); echo 'Located: ' . $row[&ap ...

How to display JSON data on the current page instead of a pop-up window in Laravel

Currently, I am in the process of developing a Single Page Application (SPA) using Laravel and Vuejs. My goal is to allow users to sign in with their Github account on a popup window. However, I have encountered an issue where the authorization callback fu ...

How can I integrate live data from a MySQL database to automatically update tables on a website?

I have developed a basic application using C# and .NET, with MVC architecture and a MySQL database linked to my server. I have utilized ADO.NET database models to automatically generate static data in my views from the models saved in the database, with ...

The function setState() is not performing as expected within the useEffect() hook

After retrieving data from my Mongo database, it's returned as an object within the useEffect hook function, specifically in the response. I then initialize a state called myorders with the intention of setting its value to the data fetched from the A ...

Using Django to Display a Line Chart with Data from a Dictionary in a Template

I have a dictionary that was generated in the views.py file. The structure of the dictionary is as follows, but it contains data for an unspecified number of enterprises: { enterprise1: {'Year': ['2014/2015', '2016/2017', &ap ...

Utilizing BEM Class Names in React

How can I utilize the Post component in a way that assigns unique classes to new and old posts following BEM recommendations? Assign a unique className to every element Avoid cascading dependencies like (.posts-new post or .posts-old post) Each component ...

Downloading Laravel Excel Files via an Ajax Call

Is it possible to generate an Excel file using Laravel with PHPSpreadsheet (PHP lib) and then send the XLSX file to the frontend for download? JSX Section axios .get( "/excel/export/dashboardTable", {} ) .then(resp => { //success call ...