fetch
훅은 데이터를 비동기적으로 가져오기 위한 것입니다. 경로를 렌더링할 때 서버측에서 호출되고 탐색할 때 클라이언트 측에서 호출됩니다.
$fetchState.pending
: 클라이언트 측에서 fetch
를 호출했을 때 placeholder를 보여줄 수 있다.$fetchState.error
: error 메세지를 보여줄 수 있다.$fetchState.timestamp
: 마지막 fetch의 시간. keep-alive
로 캐싱할 때 유용하다.<button @click="$fetch">Refresh</button>
또는
export default {
methods: {
refresh() {
this.$fetch()
}
}
}
activated
hook과 조합하여 30초 동안 fetch
를 캐시할 수 있다.<template> ... </template>
<script>
export default {
data() {
return {
posts: []
}
},
activated() {
// Call fetch again if last fetch more than 30 sec ago
if (this.$fetchState.timestamp <= Date.now() - 30000) {
this.$fetch()
}
},
async fetch() {
this.posts = await fetch('https://api.nuxtjs.dev/posts').then(res =>
res.json()
)
}
}
</script>