Vue.js: Why isn't the view updating when the data changes?

<div id="app">
<h1> Latest News </h1>
<div v-for="CurArticle in articles">
<div id="title">
<h2>{{CurArticle.title}}</h2>
</div>
<div id="content">
<p>{{CurArticle.content}}</p>
</div>
</div>
</div>




<script>
const API_KEY = "XXXXXXXXXX";
const url = "https://newsapi.org/v1/articles?";



const app = new Vue({
el: '#app',
data:{
    articles: [{
    title:"News Title", content: "Lorem Ipsum"
    }]
    },
mounted(){
    axios.get("https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=XXXXXXXXXXX").then(function(reply){
    this.articles = reply.data.articles;
    //app.$set(this.news, response.data.articles);
    console.log(reply.data.articles);
    }).catch(function(error){
    console.log(error);
    })
}
});

</script>

The data does not populate correctly. Additionally, every time I attempt to view the data/response object via the console, I encounter an error stating "Reference Error: data/reply is not defined". The AJAX call operates without any issues.

Answer №1

When making your axios request, ensure that you are aware of the context in which this is being used within the success callback. If you are concerned about it not pointing to the Vue instance due to using a normal function syntax, consider utilizing the fat arrow => function syntax instead:

mounted(){
    axios.get("your URL").then((response) => {
    this.news = response.data.articles;
    console.log(response.data.articles);
    }).catch(function(error){
    console.log(error);
    })
} 

Alternatively, you can declare a variable vm at the beginning of the mounted block and assign it to the Vue instance to maintain the correct context like so:

mounted(){
    var vm = this;
    axios.get("your URL").then(function(response) {
    vm.news = response.data.articles;
    console.log(response.data.articles);
    }).catch(function(error){
    console.log(error);
    })
} 

Answer №2

    <div v-for="CurrentArticle in articles">
        <div class="article-container">
        <h1>{{CurrentArticle.headline}}</h1>
    </div>

id must be unique, but you can use a class. Make sure the data attribute is defined as a function.

data(): {
 articles: [{
  headline:"Breaking News", summary: "Lorem Ipsum"
  }]
}

Answer №3

If you're looking to utilize arrow functions, consider the following example:

fetch("/static/data/new_data_table.json", {
            method: "GET",
            headers: {
              'Content-Type': 'application/json',
              'Accept': 'application/json'
            }
          }
        )
          .then((response) => {
            return response.json()
          }).then ((json) => {
          this.updatedJson = json
        }).catch( (error) => {
        })

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

Cause a malfunction in the triggering function of jQuery

$(document).ready(function(){ jQuery("#but1").bind("click",function(e){ alert(e.name); }); jQuery("#but1").trigger({name:'Dmy', surname:'My'}); }); The information doesn't seem to be getting passed correctly a ...

Is there a way to trigger this pop-up after reaching a certain percentage of the page while scrolling?

I've been working on a WordPress site that features an "article box" which suggests another article to users after they scroll to a certain point on the page. However, the issue is that this point is not relative but absolute. This means that the box ...

Why isn't my List<string> being retrieved from the MVC Controller in an $ajax request?

I am attempting to generate customized lists in my cshtml file through an ajax request. .ajax({ type: "GET", cache: false, url: "@Url.Action("getValidationLists")", contentType: "application/json", dataType: "json", ...

Is there a way to organize products by assigning each one its own unique group ID?

Challenge I am experiencing an issue where I have multiple products with different descriptions, so I needed to group them in corresponding dropdowns. However, when I modify the value in the dropdown for a particular product, it only updates the values for ...

Establishing a socket connection within a routing function

I am in the process of organizing my express node app by consolidating all socket.io functionality within express routes or router pages (based on a solution found here: Nodejs include socket.io in router page). Strangely, despite my efforts, I cannot esta ...

A guide on implementing a confirmation box with jquery confirm plugin for form submission

After submitting a form, I want to display a confirmation message without using the typical method of "return confirm("Are You Sure?")". I decided to utilize JQuery Confirm in this way: @using (@Html.BeginForm("SubmitTest", "HydrostaticReception", FormMe ...

In JavaScript, how does the usage of parentheses change the functionality of a function?

function find() { console.log("Request handler 'find' was called."); } function display() { console.log("Request handler 'display' was called."); } exports.find = find; exports.display = display; There ...

Increase the offsetHeight of the entire class

I am faced with a challenge on my webpage where elements within a single class have varying heights based on the size of their text content. To address this, I need to increase the height of all these elements by 20px upon page load. var visibleposts = do ...

Attempting to wipe out a request using ajax to access relationship entities in a ruby on rails framework

I'm currently working on implementing an ajax request to delete a "budget" (known as "orçamento" in Portuguese). These budgets are associated with a "cadastre", where each cadastre can have multiple budgets. Below, you can find the components involve ...

The content rendered by React server side rendering is not accurate

Currently, I am in the midst of developing a react web application that utilizes React, Redux, and React Router, with server-side rendering facilitated by Express. The issue that I am encountering is rather complex to articulate. Allow me to break it down ...

Combine a segment from two arrays into a single array

I have two arrays and I want to merge them into one while extracting only certain elements... I am using axios with vueJS. (9) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}] 0: Nombredejours: 1.5 Task: {id: "52edcb0e-450f-4de7-b70d-b63e0 ...

Press the mouse button to position the camera close to an element in Three.js

Trying to implement a click to zoom feature with Three.js, I have a canvas and an object loaded in it. When clicking, I want to position the camera near the point of intersection for a zoom effect. Here is my current code, but it's not working as exp ...

Receiving an error in Vue when trying to access a nested object property that is potentially

I am encountering a Vue error in the console that says "cannot read property (property name) of undefined". Even after trying to implement v-if, I am still getting the same error. It seems like the object I am trying to access does not exist or is not defi ...

Refrain from using inline JavaScript code within your

Here is the basic structure of my code: <a href="javascript:void(0);" onClick="viewServices(1)">Services</a> <a href="javascript:void(0);" onClick="viewServices(43)">Services</a> <a href="javascript:void(0);" onClick="viewServic ...

Tips for detecting a new day with server-side JavaScript

I am currently developing a website that includes a schedule for teachers. I have encountered the need to delete elapsed days data from a database. What is the most effective method to monitor when it is exactly 12 midnight? If I were to use setInterval( ...

Is it true that core JavaScript is not compatible with AngularJS projects?

While this may seem like a simple question to some, I have been struggling to find the answer for quite some time now. Why is it that native javascript methods like onclick do not work in my Angular 2 project? Below is a sample code snippet for reference: ...

Troubleshooting 404 Error When Using Axios Put Request in Vue.js

I'm trying to update the status of an order using Axios and the Woocommerce REST API, but I keep getting a 404 error. Here's my first attempt: axios.put('https://staging/wp-json/wc/v3/orders/1977?consumer_key=123&consumer_secret=456&apos ...

Prevent the user from selecting an option if the value is already present

In the process of creating a library membership form, I am utilizing an ajax request to populate the student list in a select option. The goal now is to disable the options for students who are already members of the library. View of the Form <div cla ...

Retrieve a variable from the context and assign it to the Angular scope

I'm having trouble accessing the sourcePath in the controller $scope. This is the code I have: (function() { var sourcePath; sourcePath = 'app/assets/javascripts/shared/controllers/some_controller.coffee'; angular.module("shared"). ...

Display Quantity of Current Website Visitors

Similar Question: how to track website visitors using java script or php I am looking to retrieve the current number of viewers on a webpage that has an embedded stream. Is there a method to accomplish this utilizing PHP and AJAX, in order to display ...