Nuxt (>= 2.12) Fetch
June 12, 2020The easiest way to fetch data using Nuxt is via asyncData, as a lot of things is handled for you (loading animation, data merging, state management, etc) and it just works.
If you need more control, you should use fetch.
- Render UI based on
$fetchState
(loading, error and success) - Have access to
this
/ page component. - Ability to disable
fetchOnServer
forcing fetch to be called on client side only - Ability to call
this.$fetch()
- Enable fetch cache
Code
<template>
<div>
<div v-if="$fetchState.pending">Loading ...</div>
<div v-else-if="$fetchState.error">Error: {{ $fetchState.error.message }}</div>
<div>
{{ title }}
</div>
</div>
</template>
<script>
export default {
async fetch() {
// const HOST = 'http://localhost:8080' // required for server-side fetch
// const url = new URL(`/data/test.json`, HOST)
const url = 'https://jsonplaceholder.typicode.com/posts/1'
// alternatvely, you could use $axios or $http
const res = await fetch(url)
const data = await res.json()
this.title = data.title
},
data() {
return {
title: null
}
},
}
</script>
References:
- algo-trading
- algolia
- analytics
- android
- android-ktx
- android-permission
- android-studio
- apps-script
- bash
- binance
- bootstrap
- bootstrapvue
- chartjs
- chrome
- cloud-functions
- coding-interview
- contentresolver
- coroutines
- crashlytics
- crypto
- css
- dagger2
- datastore
- datetime
- docker
- eslint
- firebase
- firebase-auth
- firebase-hosting
- firestore
- firestore-security-rules
- flask
- fontawesome
- fresco
- git
- github
- glide
- godot
- google-app-engine
- google-cloud-storage
- google-colab
- google-drive
- google-maps
- google-places
- google-play
- google-sheets
- gradle
- html
- hugo
- inkscape
- java
- java-time
- javascript
- jetpack-compose
- jetson-nano
- kotlin
- kotlin-serialization
- layout
- lets-encrypt
- lifecycle
- linux
- logging
- lubuntu
- markdown
- mate
- material-design
- matplotlib
- md5
- mongodb
- moshi
- mplfinance
- mysql
- navigation
- nginx
- nodejs
- npm
- nuxtjs
- nvm
- pandas
- payment
- pip
- pwa
- pyenv
- python
- recylerview
- regex
- room
- rxjava
- scoped-storage
- selenium
- social-media
- ssh
- ssl
- static-site-generator
- static-website-hosting
- sublime-text
- ubuntu
- unit-test
- uwsgi
- viewmodel
- viewpager2
- virtualbox
- vue-chartjs
- vue-cli
- vue-router
- vuejs
- vuelidate
- vuepress
- web-development
- web-hosting
- webpack
- windows
- workmanager
- wsl
- yarn