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

Finding a potential data breach in Node.js, MongoDB, and Chrome, exposed passwords are

My web app is built using nodejs with mongodb as the database backend, and I am encountering an issue with Chrome browser flagging my login process via passport.js as an exposed password. How can I prevent this warning? Should I implement something like Bc ...

Checking the image loading functionality with Cypress

I am interested in testing Cypress to verify that an image is successfully loaded onto a page. Here is a snippet of my source code: import React from "react"; export default class Product extends React.Component { render() { return ( <div ...

Retrieving a MongoDB collection using its unique ID

Here's a query that may seem straightforward. I have two collections in MongoDB - one named "users" with an objectId, and the other named "listings" which has the userId. I am looking to retrieve documents from the listings collection by searching fo ...

Python unable to extract data from a JSON file

My JSON data contains information about a cluster with various attributes and values. I am using the json module in Python to parse this data and extract specific information. The key information I am interested in extracting is: Name Value operational-s ...

Generating a CSV file with a list of Bitcoin addresses in Python by writing them line by line in JSON format

Currently, I am using the onename API to retrieve the bitcoin addresses of all users. My current approach involves obtaining user information in a JSON-like list format and then saving the output to a file. Here's an example of the output: [{'0 ...

Executing JavaScript code from an external HTML file

My goal is to create and utilize native web components by defining them as HTML files containing markup, CSS, and Javascript all bundled together in one file, similar to how Vue handles .vue files. These components would be fetched from an external compone ...

Encountering a Basic React Issue: Unable to Implement @material-ui/picker in Next.js

I'm currently attempting to integrate the @material-ui/pickers library into my Next.js application. In order to incorporate the Picker provider, I followed the guidance provided in the Next.js documentation by adding the _app.js file inside /pages: i ...

Filtering out specific properties from an element within a JavaScript forEach loop

const findBloodType = bloodCodeArray.find(bloodCode => bloodCode.code.toUpperCase() === bloodType.toUpperCase()).code; In my Angular code, I am trying to retrieve just the 'code' property of the 'bloodCode' element using a callback ...

Exposing the location data in vue-test-utils tests

My goal is to start each test with a fresh setup, such as creating a new localVue instance for each test. However, I have noticed that the state seems to be leaking between unit tests despite using vue-test-utils and jest with vue-router. To workaround t ...

Is the mounted hook not being triggered in a Nuxt component when deploying in production (full static mode)?

I have a component that is embedded within a page in my Nuxt project. This particular component contains the following lifecycle hooks: <script> export default { name: 'MyComponent', created() { alert('hello there!') }, ...

Is it possible to conceal any spans that are in close proximity to the cursor when hovered over?

Currently, I am working on a project that involves multiple spans placed side by side, with each span containing a letter of the text. My aim is to create a functionality where hovering over one of these spans will not only hide that particular span but al ...

Is there a way to enable drag and drop functionality on a dynamically created table using AJAX?

I have been successfully using the TableDnD plugin for drag and drop functionality on table rows. However, I am now facing an issue with dynamically generated tables via AJAX. The code doesn't seem to work as expected when it comes to drag and droppin ...

When the margin-left changes, SVG begins to flicker and shake in a marquee effect

I've been experimenting with a marquee effect using vanilla JS. The effect is working, but I'm encountering some shaking issues with SVG and images as they move. <div class="marquee"> <h1>Nepal <svg version="1.1&qu ...

AngularJS is displaying a blank Galleria when images fail to load

I have a code snippet similar to the following var dummyAlbum = [ {image: 'http://i.imgur.com/7Osllxil.jpg'}, {image: 'http://i.imgur.com/YACmI1G.jpg'}, {image: 'http://i.imgur.com/af4ZDy8.jpg'}, {image: &apos ...

Unresolved promise: Internal server issue

I encountered an exception while working on my Nativescript app. EXCEPTION: Uncaught (in promise): Server error JS: ORIGINAL STACKTRACE: JS: Error: Uncaught (in promise): Server error JS: at resolvePromise (/data/data/com.yourdomain.appname/files/app/ ...

Notification for Unsuccessful Login Attempt on the Client Side

In my node.js project, I have implemented a login form that sends data to the server.js file as URL parameters. When the sent data is verified against registered users, the client is successfully logged in. However, I am facing an issue on how to notify th ...

Exploring the Safari browser with Polymer 2.0

Looking for some help with a question I have... I've been experimenting with the new Polymer 2.0 preview on Safari, but it doesn't seem to be working correctly. I'm using a simple code (just my-element) in the index.htm file, loading the pol ...

Use Yii2 to pass an ID when a button is clicked in order to render a partial using

On the index page, I display all the rows and some fields from my model. When a button is clicked, I want a modal to appear with all the data from the corresponding row. When the button is clicked, I need an ajax call to render a partial view. This will i ...

Yet another error encountered: "Headers cannot be set after they have already been sent to the client" when submitting the form

Whenever I try to submit text to a single-field form on my node.js server, I encounter the following error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader (_http_outgoing.js:485:11) ...

Utilizing TypeScript Variables within a Jquery Each Iteration

I have a variable named tableIndexNumber that I need to use in different methods. When trying to access this variable, I use "this.tableIndexNumber" and it works fine. However, I face an issue when using it inside a jQuery each loop because the HTML elemen ...