Learning to access JSON data stored in local storage and presenting it in a VUE component

I'm having trouble displaying the content of a json file (books.json) as a list on my website using VUE. Here is the code I'm currently working with:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<html>
<head>
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4234372702706c776c7375">[email protected]</a>/dist/vue.js"></script>

</head>
<body>
  <div id="app">
    <span>{{items}}</span>
    <ul>
      <li v-repeat="items">
         <span class="name">{{books.name}}</span><br>
         <span class="genre">{{books.genre}}</span>
      </li>
    </ul>
  </div>
</body>
 

<script>

    var app= new Vue({
        data: {
          items: null
        },

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

        methods: {
          fetchData: function () {
          var self = this;
          $.get( 'books.json', function( data ) {
              self.items = data;
          });
          }
        }
    });
</script>
 
</html>

Could someone assist me with this issue, please? Thank you

Answer №1

It is recommended to update your vue version. I have made the necessary changes by replacing v-repeat with v-for and mounting it to #app. You can also utilize el within your vue instance instead of $mount. Furthermore, I've updated the data to be a function as per the guidelines (https://v2.vuejs.org/v2/guide/components.html#data-Must-Be-a-Function)

const app = new Vue({
  data() {
    return {
      items: null
    }
  },

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

  methods: {
    fetchData: function () {
      var self = this;
      
      // test data
      this.items = [{
        name: 'Test-Name',
        genre: 'My Genre'
      }];
      
      // Commented out because we don't have this file.
      /* $.get( 'books.json', ( data ) => {
        self.items = data;
      }); */
    }
  }
});

app.$mount('#app');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <span>{{items}}</span>
  <ul>
    <li v-for="book in items" :key="book.name">
      <span class="name">{{book.name}}</span><br>
      <span class="genre">{{book.genre}}</span>
    </li>
  </ul>
</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

The JavaScript in the Laravel file isn't functioning properly, but it works perfectly when incorporated via CDN

Successfully implemented code: <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script> <script type="text/javascript"> var textWrapper = document.querySelector('.ml6 .letters'); textWrapper.in ...

Is it possible to retrieve data using a POST request?

An organization has assigned me an Angular task. They have given the following guidelines, however, the API URL is not functioning: Develop a single-page Angular application using the provided API to fetch sports results and organize them in a displayed ta ...

Server.js node is unresponsive and throwing an error message

Currently, I have started working with expressJs nodeJs but I am facing an issue at the beginning when trying to run the node server.js command. It seems like there might be a missing module that needs to be installed, but I am unsure which one is missing. ...

A pair of distinct identifiers in an SQL database

I am currently working with a table containing the following fields: Users (Id, Uid, Name, Sex...). In this structure, the Id is set to auto increment, while the Uid is generated uniquely by my script using a combination of capital letters and numbers su ...

Encountering an error with jQuery being undefined while utilizing an Immediately Inv

I'm looking to add a Live Search feature to a webpage that will filter matches from an array of objects when a search term is entered in the search box. However, I am encountering an issue while iterating through the array items using a forEach loop ...

Enabling CORS for certain routes while disabling it for others using Vue

After days of troubleshooting, I am still unable to pinpoint the issue. I have my own API set up on my server, and when I test it with Postman, everything runs smoothly. Similarly, when I connect to it using VueJS, everything works fine as well. However ...

Encountering issues while trying to install Java using NPM

Encountering errors when attempting to run the following command to install java dependencies for NPM. NPM install -g java In need of assistance to fix this error. C:\WINDOWS\system32>npm i -g java [email protected] install C:\D ...

Accessing the setter's name from within a Javascript setter function

Can anyone help me figure out how to get the name of the setter that is called when assigning a value? Here's an example: var b = {}; var a = { set hey(value) { b[<name of setter>] = value; } } I would like to retrieve the name of the set ...

Encountering an error message while starting up a Node Express server

Hello everyone, I am currently new to webpack and attempting to run my own server using 'node server.js'. However, I encountered an issue with the following error message: $ node server.js /path/to/server.js:3 import path from 'path' ^ ...

Menu options disappearing upon clicking within the container area

Every time I click inside the dropdown menus, they unexpectedly close. This issue is persistent in both the Login menu and the nav bar. Although I’m not a seasoned web developer, I suspect it’s just a simple error that I’ve been overlooking all day ...

What is the best method to determine offsetTop in relation to the parent element instead of the top of

I have a straightforward inquiry: How can one determine the offsetTop of a child element in relation to its parent element rather than the top of the window? The definition of offsetTop indicates that it should give the distance by which a child element i ...

In relation to the issue with JSON parsing

<?php $url = "http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=YOURAPI"; $json = file_get_contents($url); $data = json_decode($json, true); $data['city']['name']; foreach ($data['list'] as $da ...

Combine two data types into one using Serde

Currently, I am working on a project that interacts with a web service and receives JSON data. The issue arises when a specific property is not present in the response; it returns an empty object with all fields as empty strings instead of excluding the v ...

How can I identify duplicate values within two distinct javascript objects?

Consider two sets of JavaScript arrays containing objects: var allUsers=[{name:"John",age:25},{name:"Emily", age:30},{name:"Michael",age:22}] and var activeUsers=[{name:"John",status:"active"},{name:"Sarah", status:"active"}] I am attempting to iterat ...

Incorporate an Ajax request onto an existing link within a div element

Here is what I have: <div id="div-for-ajax-onclick"> <a href="http://www.google.com">Link to google</a> </div> $("#div-for-ajax-onclick").click(function() { // update database }); I am looking for a solution where if someone c ...

Extract string from deeply nested JSON data

Currently, I am developing a middle-man service that serves as a content management system. The process involves receiving a complete and intricate JSON file on my server, which needs to be distributed to clients in JSON format (let's skip over the va ...

The Express router is failing to recognize the mongoose model

Currently, I am developing a node.js application and encountering an issue where I receive a reference error stating that Post is not defined every time I run this specific code. Interestingly, when I move the post route from submit.js to app.js, the code ...

Despite the presence of data, MongoDB is not returning any values

I am currently working on a code that utilizes $geoNear to find the closest transit stop to a given GPS coordinate. The issue I am facing is that the result sometimes returns undefined, even though I have confirmed that the data exists in the STOPS collect ...

utilization of jq json for dynamic http requests

My goal is to dynamically pass the key and values from a JSON file into InfluxDB. Below is the batch file I am using : The JSON file linked below contains the following data: { "status": "UP", .... (JSON data continues) The batch ...

decoding JSON object into a table

click here for image I received an API response in JSON format, displayed in the picture. My goal is to parse it so that I only extract Rows and Columns from Table - 0, excluding all others. I attempted various solutions, including the one below, but none ...