Update the VueJS application by loading and replacing the existing JSON data with new information

Is there a way to dynamically re-render the entire v-for loop and DOM after fetching and loading new JSON data to replace the current one? I want to be able to click on different options and have the products updated.

Vue.use(VueResource);    
var productsList = new Vue({
    el: '#vue',
    data: function () {
        return {
            products: []
        };
    },
    ready: function () {
        this.$http.get('data/data.json').then(function (response) {
            this.products = response.data;
        });
    },
    methods: {
        loadProducts: function (url) {
            this.$http.get(url).then(function (response) {
                this.products = response.data;
            });
        }
    }
});

Answer №1

To automatically update your DOM, the code above is suitable. However, there are 2 errors to address and 1 important consideration to keep in mind.

In JavaScript, anonymous functions have different scopes. This means that using an anonymous function like function(response) can cause you to lose the scope of the Vue instance, as represented by this. To handle this situation, you can either utilize arrow functions if supported in your project, or save the value of this into another variable before entering the anonymous function.

Vue.use(VueResource);    
var productsList = new Vue({
el: '#vue',
data: function () {
    return {
        products: []
    };
},
ready: function () {
    var self=this;
    this.$http.get('data/data.json').then(function (response) {
        self.products = response.data;
    });
},
methods: {
    loadProducts: function (url) {
        var self=this;
        this.$http.get(url).then(function (response) {
            self.products = response.data;
        });
    }
}
});

If you encounter an error in the browser with undefined products while using this particular code, it indicates a problem that needs to be resolved.

Answer №2

Upon updating the products data, the DOM will automatically reflect the latest data changes as Vue data is reactive. One issue in your code is potentially having the incorrect use of this within the this.$http block. Instead of using the traditional function() syntax, consider using an arrow function, which does not bind its own this, arguments, super, or new.target, like so:

Vue.use(VueResource);    
var productsList = new Vue({
    el: '#vue',
    data: function () {
        return {
            products: []
        };
    },
    ready: function () {
        this.$http.get('data/data.json').then((response) => {
            this.products = response.data;
        });
    },
    methods: {
        loadProducts: function (url) {
            this.$http.get(url).then( (response) => {
                this.products = 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

Injecting script into a webpage and initiating an ajax request prior to receiving a response

Trying to accomplish something a bit complex that I believe is feasible, or perhaps someone could offer a suggestion on how to achieve it. At website A, there is a database containing booking data. At website B, the goal is to display information about w ...

What could be causing the Express server to return an error despite everything being in order?

I am new to exploring express.js and attempting to create a basic sign-in example server. I have set up a database object with a users array containing objects, each with email and password properties. Despite using body-parser to convert the body into a j ...

Is it recommended to run JavaScript functions obtained from REST APIs?

Our single page application is built on Angular 4 and we are able to change input fields based on customer requirements. All the business rules for adjusting these fields are coded in JavaScript, which runs on the Java Platform and delivers the output thro ...

Tips for extracting JSON data from a JSON array into a RecyclerView in Java on Android devices

I am facing an issue with parsing JSON data into my RecyclerView. Whenever I encounter JSON data that contains array data, my app crashes when attempting to retrieve it. Does anyone have a solution for this problem or perhaps a sample code with a similar s ...

Adding an arrow to a Material UI popover similar to a Tooltip

Can an Arrow be added to the Popover similar to the one in the ToolTip? https://i.stack.imgur.com/syWfg.png https://i.stack.imgur.com/4vBpC.png Is it possible to include an Arrow in the design of the Popover? ...

Guide on displaying content in two different tabbable ID's when one tab is selected in a Rails 3.2 App using Twitter Bootstrap's Tabbable Tabs

My implementation using Twitter Bootstrap's bootstrap-tab.js includes: <ul class="tabnavcenter" id="myTab"> <li class="active"><a href="#home" data-toggle="tab">about</a></li> <li><a href="#tab2" data-togg ...

Unraveling JSON data within an AngularJS controller

I'm facing an issue with exposing a field in my AngularJS controller. The problem arises when a JSON 'owner' object is returned by a webservice, containing a field named 'Cave'. If this 'Cave' field has a null, empty, or ...

Rotate images using a JQuery plugin without using HTML tags, solely through passing the images in JavaScript

I am currently working on creating a jQuery image rotator from scratch. While I know there are simple jQuery sliders/rotators available, I specifically want to include the image files directly within the JS code. I do not want to use this HTML structure: ...

Invalid number of arguments for pure functions

I am currently facing an issue in angular2 (rc-1) where I am passing an array of strings to my function through component binding. However, when the array length exceeds 10, an error occurs: Unsupported number of argument for pure functions: 11 This erro ...

Conditional compilation in Laravel Mix allows for specific code blocks to be

I'm currently working on a Laravel project and I need to introduce some conditional statements. Within the root folder of the project, there's a file called module_statuses.json which contains JSON variables like this: { "Module1": true, ...

Is there a way to use JavaScript to automatically open a URL at regular intervals?

List of URLs in JavaScript: var websites = ['https://www.google.com', 'https://www.msn.com', 'https://stackoverflow.com']; I have an array containing multiple website URLs. My goal is to open each URL in a new tab or window e ...

How to efficiently update a nested array within the state of a React

Although the onChange function is working as expected, I am facing issues with updating the features in the state. Despite numerous attempts, I haven't been able to find examples similar to what I'm trying to achieve, so I decided to seek help. ...

Is there a way to retrieve the BrowserRouter history from outside of the BrowserRouter component?

Here is a simplified code snippet (using react-router-v5). I am trying to figure out how to access BrowserRouter's history in the logout_Handler() function, even though I am "outside" BrowserRouter. I came across this answer on How to access history ...

Is it possible to refresh data efficiently using web scraping tools, similar to how it

While researching web scraping in Python, I consistently found references to BeautifulSoup and Selenium as the primary tools for retrieving HTML and JavaScript content from websites. One thing that has eluded me is finding a method to automatically update ...

Ways to modify client socket from JavaScript to PHP

Looking for a way to convert a client socket from JavaScript to PHP in order to receive data from the server socket? Check out the PHP socket Bloatless library here. This is an example of the Client Javascript code: <script> // connect to chat appl ...

Troubleshooting loading specific story types on hacker news API with Angular.js

I have been working on a hacker news client using the official hacker news firebase API and Angular.js. Everything seems to be working fine except for the 'jobstories' posts, which are not rendering on the screen even though the story IDs are bei ...

Global error handling for URQL GraphQL mutation is a critical aspect that needs to be effectively implemented

Here's the technology stack I'm using: react v17.0.2 graphql v16.8.0 graphql-ws v5.14.0 urql v4.0.5 I rely on Hasura Actions to interact with a REST API and am in need of a solution for handling global errors for all mutations. For instance, I ...

Exploring JSON Objects and Arrays within a Java Programming Environment

Currently, I am immersed in the process of creating a Java class within Android Studio that focuses on constructors with getters and setters, specifically to handle JSON arrays and objects. The JSON data format provided above serves as a reference for th ...

Identify whether the application is built with nextJS, react, or react-native

I'm currently developing a library for React applications and I anticipate that certain features will function differently depending on the environment. I am seeking a method to identify whether the current environment is a ReactJS application (creat ...

Angular custom window injection

Currently, I am working on an Angular application that is housed within an Android WebView. To facilitate communication with my Android application, I have made an object accessible at the window level: window.MyAndroidApp This object contains various me ...