The fetch method works the same as the asyncData method, except it is called after the created Vue lifecycle hook – in other words, after initiating the component. Like the asyncData method, it can be used asynchronously, too; for example, you also can use it to set the data in the page component:
// pages/users/index.vue
<li v-for="user in users" v-bind:key="user.id">
<nuxt-link :to="`users/${user.id}`">
{{ user.name }}
</nuxt-link>
</li>
import axios from 'axios'
export default {
data () {
return { users: [] }
},
async fetch () {
let { data } = await axios.get
('https://jsonplaceholder.typicode.com/users')
this.users = data
}
}
Note that the data method must be used with the fetch method to set the data. Since it is called after the page component is initiated, we can use the this keyword to access the object in the data method. We also can use this method to set the data...