Reputation: 51
I have a code that gets json from RESTful API. but It only shows .container and It says that there's nothing in items array. the mysterious thing is it doesn't show any errors about it. so I was trying to debug it showing result from fetch using console.log, so I added like let result = await fetch('video').then(res => res.json())
under the code but It doesn't show anything on browser console. seems like It doesn't run the async getData
function but I have no clue..
<template lang="pug">
.container
.columns(v-for="n in lines")
.column.is-3.vid(v-for='item in items')
.panel
p.is-marginless
a(:href='item.videoId')
img(:src='item.thumbnail')
.panel.vidInfo
.columns.hax-text-centered
.column
.panel-item.reddit-ups
span {{ item.score }}
i.fa.fa-reddit-alien.fa-2x
.panel-item.reddit-date
i.fa.fa-calendar.fa-2x
</template>
<script>
export default {
name: 'main',
data: () => ({
items: [],
lines: 0
}),
async getVideo () {
this.items = await fetch('/video').then(res => res.json())
this.lines = Math.ceil(this.items.length/4)
}
}
</script>
Upvotes: 1
Views: 900
Reputation: 9201
There are few issues in your code, and console should warn you about them.
First define data object as ES6 Object Method Shorthand, try to avoid arrow functions:
data() {
return {
items: [],
lines: 0
}
}
Then I guess get video is method, so It should be placed under the methods object:
methods: {
async getVideo () {
this.items = await fetch('/video').then(res => res.json())
this.lines = Math.ceil(this.items.length/4)
}
}
I don't know where you want trigger this method (on click, when instance is created or mounted), but I will use created hook
<script>
export default {
name: 'main',
data() {
return {
items: [],
lines: 0
}
},
methods: {
// I don't think you need async/await here
// fetch would first return something called blob, later you can resolve it and get your data
// but I suggest you to use something like axios or Vue reource
async getVideo () {
await fetch('/video')
.then(res => res.json())
.then(items => this.items = items)
this.lines = Math.ceil(this.items.length/4)
}
},
created() {
this.getVideo()
}
}
</script>
Upvotes: 1