Reputation: 397
I need to fetch latest data when mount vue component, but need to check the props first. but it allways getting undefined. it looks like this code
Vue.component('book', {
props: ["showLatest"],
data: function() {
return {
books: null
}
},
template: '<ul><li v-for="book in books">This is a book {{ book.name }} <small><i>{{ book.publisher}}</i></small></li></ul>',
method: {
fetch: function() {
this.books = [
{
name: "Latest 1",
publisher: "publisher_test1"
},
{
name: "Latest 2",
publisher: "publisher_test2"
},
{
name: "Latest 3",
publisher: "publisher_test3"
}
];
}
},
mounted: function() {
console.log(this.showLatest);
if(!this.showLatest) {
this.books = [
{
name: "Test 1",
publisher: "publisher_test1"
},
{
name: "Test 2",
publisher: "publisher_test2"
},
{
name: "Test 3",
publisher: "publisher_test3"
}
];
} else {
this.fetch();
}
}
})
var app = new Vue({
el: '#app',
data: {
message: 'Digital Library!'
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
{{ message }}
<book :showLatest="true"></book>
</div>
Why showLatest
always getting undefined
. if this is not good approach, how to make it work..?
Hopefully anyone can help
Thanks in advance
Upvotes: 0
Views: 1055
Reputation: 1
The prop should be written in kebab-case format when it's used in parent like <book :show-latest="true"></book>
or just <book show-latest></book>
and in the child component fix method
to methods
:
Vue.component('book', {
props: ["showLatest"],
data: function() {
return {
books: null
}
},
template: '<ul><li v-for="book in books">This is a book {{ book.name }} <small><i>{{ book.publisher}}</i></small></li></ul>',
methods: {
fetch: function() {
this.books = [
{
name: "Latest 1",
publisher: "publisher_test1"
},
{
name: "Latest 2",
publisher: "publisher_test2"
},
{
name: "Latest 3",
publisher: "publisher_test3"
}
];
}
},
mounted: function() {
console.log(this.showLatest);
if(!this.showLatest) {
this.books = [
{
name: "Test 1",
publisher: "publisher_test1"
},
{
name: "Test 2",
publisher: "publisher_test2"
},
{
name: "Test 3",
publisher: "publisher_test3"
}
];
} else {
this.fetch();
}
}
})
var app = new Vue({
el: '#app',
data: {
message: 'Digital Library!'
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
{{ message }}
<book :show-latest="true"></book>
</div>
Upvotes: 2