VueRouter 基础教程系列 🎉
在 Vue 中请求服务端数据的时机有两种:
- 路由导航完成之前:在路由的生命周期期间发起请求。
- 路由导航完成之后:在路由组件生命周期期间发起请求。
{
methods: {
getPost() {
this.loading = false;
fetch('/data').then(res => {
this.data = res.data;
this.loading = true;
});
}
}
}
路由导航完成之前
在路由生命周期钩子中发起请求,主要是在 beforeEach 或者是 beforeRouteEnter、beforeRouteUpdate 中发起请求。
export default {
data() {
return {
post: null,
error: null,
}
},
beforeRouteEnter(to, from, next) {
getPost(to.params.id, (err, post) => {
next(vm => vm.setData(err, post))
})
},
// 路由改变前,组件就已经渲染完了
// 逻辑稍稍不同
async beforeRouteUpdate(to, from) {
this.post = null
try {
this.post = await getPost(to.params.id)
} catch (error) {
this.error = error.toString()
}
},
}
路由导航完成之后
在路由组件的生命周期钩子中发起请求,主要是在 created 中发起请求。
{
data() {
return {
loading: false,
post: null,
error: null,
}
},
created() {
// watch 路由的参数,以便再次获取数据
this.$watch(
() => this.$route.params,
() => {
this.fetchData()
},
// 组件创建完后获取数据,
// 此时 data 已经被 observed 了
{ immediate: true }
)
}
}