路由数据获取
获取数据,可以有两种方式:导航完成后获取和导航完成前获取
导航完成后获取
编写post.vue,并配置好路由规则
<template>
<div class="post">
<div v-if="loading">
loading
</div>
<div v-if="post">
<h2>{{ post.title }}</h2>
<p>{{ post.body }}</p>
</div>
</div>
</template>
<script>
export default {
name: "Post",
data() {
return {
loading: false,
post: null
}
},
//组件创建完毕
created() {
//执行获取数据
this.getData()
},
methods:{
//获取数据
getData(){
this.loading=true
//开始获取数据
setTimeout(()=>{
//关闭loading
this.loading=false,
this.post={
title:'标题',
body:'内容'
}
},1000)
}
}
</script>
<style scoped>
</style>
完成后获取
使用组件内守卫 beforeRouterEnter 实现
<script>
export default {
name: "Post",
data() {
return {
loading: false,
post: null
}
},
beforeRouteEnter(to, from, next) {
setTimeout(()=>{
next(vm =>{
vm.getData()
} )
},2000)
},
methods: {
//获取数据
getData() {
this.post = {
title: '标题',
body: '内容'
}
}
}
}
</script>