Appearance
导航完成后获取数据
本节目标:理解“导航完成后获取数据”的核心思路,并能把它用于实际开发或面试表达。
当你使用这种方式时,我们会马上导航和渲染组件,然后在组件的 created 钩子中获取数据。这让我们有机会在数据获取期间展示一个 loading 状态,还可以在不同视图间展示不同的 loading 状态。
假设我们有一个 Post 组件,需要基于 $route.params.id 获取文章数据:
<template>
<div class="post">
<div v-if="loading" class="loading">
Loading...
</div>
<div v-if="error" class="error">
{{ error }}
</div>
<div v-if="post" class="content">
<h2>{{ post.title }}</h2>
<p>{{ post.body }}</p>
</div>
</div>
</template>
export default {
data() {
return {
loading: false,
post: null,
error: null
}
},
created() {
// 组件创建完后获取数据,
// 此时 data 已经被 observed 了
this.fetchData()
},
watch: {
// 如果路由有变化,会再次执行该方法
'$route': 'fetchData'
},
methods: {
fetchData() {
this.error = this.post = null
this.loading = true
// replace getPost with your data fetching util / API wrapper
getPost(
this.$route.params.id,
(err, post) => {
this.loading = false
if (err) {
this.error = err.toString()
} else {
this.post = post
}
})
}
}
}当你使用这种方式时,我们会马上导航和渲染组件,然后在组件的 created 钩子中获取数据。这让我们有机会在数据获取期间展示一个 loading 状态,还可以在不同视图间展示不同的 loading 状态。 假设我们有一个 Post 组件,需要基于 $route.params.id 获取文章数据: <template> <div class="post"> <div v-if="loading" class="loading">Loading...</div> <div v-if="error" class="error">{{ error }}</div> <div v-if="post" class="content"> <h2>{{ post.title }}</h2> <p>{{ post.body }}</p> </div> </div> </template> js export default { data() { return { loading: false, post: null, error: null, } }, created() { // watch 路由的参数,以便再次获取数据 this.$watch( () => this.$route.params, () => { this.fetchData() }, // 组件创建完后获取数据, // 此时 data 已经被 observed 了 { immediate: true } ) }, methods: { fetchData() { this.error = this.post = null this.loading = true // replace getPost with your data fetching util / API wrapper getPost(this.$route.params.id, (err, post) => { this.loading = false if (err) { this.error = err.toString() } else { this.post = post } }) }, }, }
