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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.