Is it possible to retrieve information from a JSON file using Vue.js 2?

Looking to retrieve data from a JSON file with the json data format.

[{"id":81,"body":"There are some reason to fix the issues","created_at":"2017-11-16 11:56:47","updated_at":"2017-11-16 11:56:47"}]

I have integrated vue-resource and followed the Vue syntax correctly.

import vueResource from 'vue-resource'
Vue.use(vueResource)

In my userlist component, I am attempting the following script

 export default {

    data:function(){
      return {
        list:[],
        car:{
          id:'',
          body:''
        }
      };
    },

    created: function(){
      this.fetchCarList();
    },


    methods:{
      fetchCarList: function(){
        this.$http.get('http://localhost:8080/api.js').then(function(response){
          this.list = response.data
        });
      }

    }
}

And here is the HTML loop for the component

<ul id="example-1">
    <li v-for="item in list">
        {{ item.body }}
    </li>
</ul>

I have verified that http://localhost:8080/api.js returns the data correctly. However, when using the get() method in the fetchCarList function, it does not work as expected. It works fine if I add the JSON data directly in the code.

How can I troubleshoot and resolve this issue?

Answer №1

The issue here is with scoping: the reference to `this` inside the callback does not point to the Vue instance you intended. This is because ES6 arrow functions were not used, as shown in the corrected code snippet below:

this.$http.get('http://localhost:8080/api.js').then(response => {
    this.list = response.data
});

To resolve this, you need to manually handle the context by creating a proxy variable like `var self = this` outside the callback function. Then, you can update `self.list` within the callback as shown below:

var self = this;
this.$http.get('http://localhost:8080/api.js').then(response => {
    self.list = response.data
});

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

Guide on dynamically setting environment properties in Vue.js during deployment when using it alongside a Spring Boot application

Vue Js and Springboot have been packaged together in a Jar file, with the Vue files being included as static content within the jar. Currently, UI specific environment variable properties are configured at build time using npm run build. However, I would ...

What is the best way to display an image in HTML?

I have successfully created an autocomplete search box that retrieves product names, but I am struggling to display the product photos. Here is the code snippet I am using: <asp:TextBox ID="txtContactsSearch" runat="server" Width="261"></asp:Text ...

Discover content within nested arrays - angularJS

I have a function written in angularJS that utilizes find to verify the presence of an item in an array; function checkCartItem(item) { return $scope.cart[0].cart_items.find(function(itm) { return itm.item_id === item.item_id }); } The fu ...

The download attribute in HTML5 seems to be malfunctioning when used within a React environment

I am experiencing an issue where the download button is not working as intended. Instead of downloading the images, it is redirecting to another page. I have tested this on multiple browsers, including Chrome, Edge, and my mobile device, but the problem pe ...

Tips for preventing a NodeJS script from crashing due to timeout being exceeded

Here is the issue I am encountering: I am attempting to scrape a website's content using NodeJS and puppeteer. Sometimes, my code halts with a Timeout Exceeded error. Is there a way for me to handle this timeout by implementing a function that will e ...

Client-side filtering for numerical columns using the Kendo UI Grid widget

In my Kendo UI grid widget, I have a model schema set up for a field like this: RS_LookBackDays: { type: "number", editable: true }, The columns configuration for the same field looks like this: { field: "RS_LookBackDays", title: "Rate Schedule – # Lo ...

Identifying the HTML Hidden Attribute Using JavaScript Without Dependencies

As someone working in the analytics field, I often rely on CSS selectors to address various issues. Currently, I am faced with a task on a website where I need to determine whether a <p> element is hidden or visible. There are two possible scenarios: ...

What is the best way to locate the Vue component I need to share data with?

Seeking guidance on structuring my Vue app. It features an interactive map where users can click on items, triggering a side panel to display related information. The side panel is enclosed in a new Vue(...) instance (perhaps referred to as a Vue component ...

Ways to evaluate and contrast two JSON values in JavaScript by their key names?

I am dealing with two JSON arrays that look like this: array1=[{a:1,b:2,c:3,d:4}] & array2=[{a:2,b:5,c:3,d:4}] Is there a way to determine which key in array2 has the same value as one of the keys in array1? For example, in array 1, key b has a value ...

Interact with SOAP web service using an Angular application

I have experience consuming Restful services in my Angular applications, but recently a client provided me with a different type of web service at this URL: http://123.618.196.10/WCFTicket/Service1.svc?wsdl. Can I integrate this into an Angular app? I am ...

Issue detected: Code coverage functionality in Jest is not functioning as expected

When attempting to use jest --coverage --watch, the goal is to only see coverage related to the specific component being tested and to track increased coverage as more tests are added. However, despite successfully running modified tests, the resulting cov ...

Execute the file separately using dot.js

When working on my project, I decided to include a header.def file in index.dot by using the {{#def.header}} snippet. To render the index.dot file, I utilized the following snippet: var dotjs = require('dot'); var dots = dotjs.process({ path: ". ...

`Troubleshooting a rotation problem with PhysiJS`

I've recently started working with this library and I've run into a persistent issue that has been quite challenging for me. My current setup involves two cubes, one utilizing physi.js and the other using three.js. I have a function in place to ...

Employing the next function in conjunction with an Express server during development

I currently have an express server handling my back-end operations. I am now in the process of transitioning my front-end to nextJS and would like to set up a proxy for my nextJS requests to access the port that my back-end is running on. Is it possible to ...

Tips for locating the ID of an array element based on the text or value of the element

I am trying to identify the span id of elements in an array based on their values. For instance, if the value in the array is "Yellow", I need to determine that the corresponding span's id is "test4". However, I am struggling to figure out how to extr ...

Modifying the badge status color in VueJS: A step-by-step guide

How can I dynamically change the color of the badge status based on the contract status in VueJS? Currently, the default color is yellow for pending contracts, but I want it to turn green for confirmed contracts and red for expired or declined contracts. T ...

Is there a way to store a file in a server directory using the <a href='mypdf.pdf'> tag?

I find myself in a bit of a bind. I have a document that needs to be saved in my server directory, which is attached in an <a href='mypdf.pdf'>My pdf</a> tag. The issue is that the filename, mypdf.pdf, is dynamically changing via Jav ...

Unlocking the data within an object across all Components in Vue

Recently, I've started using Vue and encountered a problem. I'm trying to access data stored inside an Object within one of my components. To practice, I decided to create a cart system with hardcoded data for a few games in the app. Below is the ...

Exploring Style Attribute Manipulation using vanilla JavaScript on Firefox

I searched for a similar question, but I couldn't find anything quite like it. I'm currently developing a JavaScript Slider plugin for various projects within our company. This requires me to manipulate styles on certain elements in the DOM. I&a ...

Is it possible for me to reply to packets that are transmitted to a website?

I'm currently working on a Python program that sends a 'hello' packet to the server and I'm wondering if I can get the server to respond based on that. Here's the code snippet I'm using to send the packet: import requests hL = ...