PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, July 24, 2022

[FIXED] How to read json from local storage and display data in VUE

 July 24, 2022     javascript, json, vue.js     No comments   

Issue

I have a json(books.json) and I want to display its content into a list, on my webpage, with VUE. I can't seem to succeed. The code looks like this:

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<html>
<head>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/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>

Can anybody help me please? Thank you


Solution

Please update your vue version. I've replaced v-repeat with v-for and mounted it to #app. You can also use el inside your vue instance instead of $mount. Additionally I've changed data to a function. (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>



Answered By - Philip
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing