Is there a way to retrieve JSON data using Vue and Axios?

I'm facing an issue trying to retrieve product data from a JSON file. Despite attempting different methods and searching for solutions online, I have not been able to find one that fits my specific scenario. As I am new to both Vue and axios, I appreciate your understanding of my limited knowledge.

Here is the code snippet I have so far:

Vue.component('products',{
data: {
    results: []
},
mounted() {
    axios.get("js/prods.json")
    .then(response => {this.results = response.data.results})
},

<!-- The rest of the template code goes here -->

The provided JSON file looks like this:

{
    "products":[
        {
            "name": "Danser Skydancer",
            "inventory": 5,
            "unit_price": 45.99,
            "image":"a.jpg",
            "new":true
        },
        {
            "name": "Avocado Zwem Ring",
            "inventory": 10,
            "unit_price": 123.75,
            "image":"b.jpg",
            "new":false
        }
    ]
}

The challenge lies in fetching the data from the JSON file specifically. However, the following approach worked successfully:

Vue.component('products',{
    data:function(){
        return{
            reactive:true,
            products: [
           {
            name: "Danser Skydancer",
            inventory: 5,
            unit_price: 45.99,
            image:"a.jpg",
            new:true
          },
          {
            name: "Avocado Zwem Ring",
            inventory: 10,
            unit_price: 123.75,
            image:"b.jpg",
            new:false
          }
            ],
          cart:0
        }
    },

<!-- The remaining template details go here -->

Answer №1

Following the warnings provided, please take the following actions:

  1. Change the name of the data array from results to products since you are using the latter as a reference name during rendering.
  2. Modify your data option to be a function that returns an object, as the data option must be a function in order for each instance to maintain an independent copy of the returned data object. Refer to the documentation for more details on this.
Vue.component('products', {
  data() {
    return {
      products: []
    }
  },

  mounted() {
    axios
      .get("js/prods.json")
      .then(response => {
        this.products = response.data.products;
      });
  },

  template: `
    //...
  `
}

<div id="products">
  <div class="productsItemContainer" v-for="product in products">
    <div class="productsItem">
 ...

Additionally, if you are not utilizing CDN (as per my understanding), it would be recommended to create the template as a component with a separate Vue file rather than defining it within template literals. Here is an example:

Products.vue

<template>
  <div id="products">
    <div class="productsItemContainer" v-for="product in products">
      <div class="productsItem">
        <!-- Other elements here -->
        
      </div>
    </div>
  </div>
</template>

<script>
  export default {
    name: 'Products',
    
    data() {
      return {
        products: []
      }
    },

    mounted() {
      axios
        .get("js/prods.json")
        .then(response => {
          this.products = response.data.products;
        });
    }
  }
</script>

After creating the component, include it in your main JavaScript file or any other location where it is required:

import Products from './components/Products.vue';

new Vue({
  el: '#app',
  
  data() {
    return {
      //...
    }
  },
  
  components: {
    Products
  }
})
<div id="app">

  <Products />

</div>

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

Ways to reset the input field of Material UI

I'm encountering an issue with clearing a form that I created using Material UI. Despite searching for solutions on Stackoverflow, none of them seem to work for me. Using setState did not achieve the desired result of clearing the form. I am looking ...

Validate selected checkbox using JavaScript

Is there a way for me to achieve real-time updates when checking and unchecking multiple checkboxes in a list? Here's the code snippet I currently have: window.onload = function () { var input = document.getElementById('listTaxi'); fu ...

When trying to append in jQuery, the error "JQuery V[g].exec is not a

Attempting to create a script that adds a table to a div within the website using the following function: function generateTable(container, data) { var table = $("<table/>"); $.each(data, function (rowIndex, r) { var row = $("<tr/>"); ...

A guide on assigning a state variable to a dynamically generated component within a React application

I need to display user data from an array and have a button for each watchlist that deletes it. Although the backend is set up with a function deleteWatchlist, I am facing an issue in setting the state of the watchlistName for each watchlist after mapping ...

Extracting the call from REST API in JSON format

Working with a third-party database using a REST API, I encountered an error response (as expected). Here is the code snippet: transaction.commit(function(err) { if (err){ var par = JSON.parse(err); \\ leading to error: SyntaxError: Unexpecte ...

Horizontal scroll box content is being truncated

I've been trying to insert code into my HTML using JavaScript, but I'm facing a problem where the code is getting truncated or cut off. Here's the snippet of code causing the issue: function feedbackDiv(feedback_id, feedback_title, feedb ...

Creating aliases for a getter/setter function within a JavaScript class

Is there a way to assign multiple names to the same getter/setter function within a JS class without duplicating the code? Currently, I can achieve this by defining separate functions like: class Example { static #privateVar = 0; static get name() ...

The issue of a non-functional grid with scroll in a flexbox

I've encountered a problem while working with the grid layout using divs and flexbox. The header, which I want to be fixed, is overlapping with the first row and I'm struggling to get the scrolling behavior right. How can I address this issue? I ...

Retrieve data from backend table only once within the bootstrap modal

How can I retrieve values from a table once a modal is displayed with a form? I am currently unable to access the values from the table behind the modal. Are there any specific rules to follow? What mistake am I making? I would like to extract the values ...

Ways to access the scrollTop attribute during active user scrolling

I've been working on a website that utilizes AJAX to keep a chat section updated in real-time. One issue I encountered was ensuring the chat automatically scrolled to the bottom when a user sent a message, but remained scrollable while new messages we ...

What is the best way to eliminate YouTube branding from a video embedded in a website?

I am currently utilizing an <iframe width="550" height="314" src="https://www.youtube.com/embed/vidid?modestbranding=1&amp;rel=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe> This setup removes the "YouTube" logo from the ...

Instantaneous data refresh using Firebase Cloud Functions

Currently, I am working on developing a chat feature in React using Firebase cloud functions. However, I am facing an issue where I do not receive updates when a user sends a message. Below is the code snippet that I have been working with: const app = a ...

Trouble arises when attempting to execute a Vue method through a Vue computed property

It seems that the issue at hand is more related to general JavaScript rather than being specific to VueJS. I have a Vue Method set up to make a Firebase Call and return the requested object, which is functioning properly: methods: { getSponsor (key) { ...

Transmitted a file from React to Node but received an empty object

After retrieving image data, I am sending this data to the server and checking if it exists using console.log. const [fileData, setFileData] = useState(""); console.log("fileData:", fileData); const getFile = (e: any) => { setFileData(e.target.fi ...

Removing invalid characters in a *ngFor loop eliminates any elements that do not meet the criteria

I am facing an issue with my *ngFor loop that is supposed to display a list of titles. fetchData = [{"title":"woman%20.gif"},{"title":"aman",},{"title":"jessica",},{"title":"rosh&quo ...

Using javascript, add text to the beginning of a form before it is submitted

I'm trying to modify a form so that "https://" is added to the beginning of the input when it's submitted, without actually showing it in the text box. Here's the script I have so far: <script> function formSubmit(){ var x ...

Choose an element from within a variable that holds HTML code

I have a specific div element that I need to select and transfer to a new HTML file in order to convert it into a PDF. The issue I'm facing is related to using AJAX in my code, which includes various tabs as part of a management system. Just to prov ...

Is there a datatable available for live data with pagination and search functionality?

I've been experimenting with datatables for real-time data, but I'm facing an issue where the search function doesn't work when my data updates. Additionally, every time I try to paginate, it reverts back to the first page. Does anyone know ...

Text element in SVG not displaying title tooltip

Looking for a solution to display a tooltip when hovering over an SVG Text element? Many sources suggest adding a Title element as the first child of the SVG element. This approach seems to work in Chrome, but not in Safari - the primary browser used by mo ...

The error message "Data type must be consistent across all series on a single axis in Google Chart" may cause confusion

I'm struggling with an error message that appears when I try to run my Google chart. Here is the code I am using to generate the chart. function (resultVal) { var arrMain = new Array();//[]; for (var i = 0; i < resultVal.length; i++) { ...