九、路由钩子与异步请求
1.路由中的钩子函数
beforeRouteEnter
:在进入路由前执行beforeRouteLeave
:在离开路由前执行
Profile.vue
<script>
export default {
name: "UserProfile",
props:['id'],
beforeRouteEnter:(to,from,next)=>{
console.log("进入路由之前");
next();
},
beforeRouteLeave:(to,from,next)=>{
console.log("进入路由之后");
next();
}
}
</script>
参数说明:
- to :路由将要跳转的路径信息
- from :路径跳转前的路径信息
- next :路由的控制参数
- next() 跳入下一个页面
- next(’/path’) 改变路由的跳转方向,使其跳到另一个路由
- next(false) 返回原来的页面
- next((vm)=>{}) 仅在 beforeRouteEnter 中可用,vm 是组件实例
2.在钩子函数中使用异步请求
安装Axios
npm install axios -s
在Main.js中引用 Axios:
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)
在static目录下新建一个目录mock,在里面创建data.json存放json数据**(假数据)**
制造假数据,另一种方式:第十章 Mock假数据
{
"name": "Lisa",
"password": 2021
}
在 beforeRouteEnter 中进行异步请求,案例代码如下:
Profile.vue
<script>
export default {
name: "UserProfile",
props:['id'],
beforeRouteEnter:(to,from,next)=>{
console.log("进入路由之前");//加载数据
next((vm)=>{
vm.getData();
});
},
beforeRouteLeave:(to,from,next)=>{
console.log("进入路由之后");
next();
},
methods:{
getData:function () {
this.axios({
method:'get',
url:'http://localhost:8080/static/mock/data.json'
}).then(function (response) {
console.log(response);
})
}
}
}
</script>
测试:
报错1:
error in ./src/views/Login.vue
Module build failed: Error: ENOENT: no such file or directory, scandir 'C:\Users\17316\Desktop\终级文档\1、笔记\1.20VUE\code\myCode\vue-elementui\node_modules\node-sass\vendor'
解决办法:
npm rebuild node-sass
报错2:node-sass报错:
卸载重装
// 卸载node-sass
npm uninstall node-sass
// 然后安装4.x版本(5.0之前)
npm install node-sass@4.14.1