404
处理 404 需要创建一个名为 NotFound.vue
的视图组件
钩子函数
类似拦截器的作用
beforeRouteEnter
:在进入路由前执行
beforeRouteLeave
:在离开路由前执行
<script>
export default {
props: ['id'],
name: "UserProfile",
//在进入路由前执行
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
是组件实例
在钩子函数中使用异步请求
-
安装Axios
cnpm install axios -s cnpm install --save vue-axios
-
main.js
引用Axiosimport axios from 'axios' import VueAxios from 'vue-axios' Vue.use(VueAxios, axios)
-
准备数据
只有
static
目录下的文件可以被访问到// 静态数据存放的位置 static /mock/data.json
-
profile.vue
在
beforeRouteEnter
中执行异步请求<script> export default { props: ['id'], name: "UserProfile", //在进入路由前执行 beforeRouteEnter: (to, from, next) => { console.log('进入路由之前'); next((vm)=>{ //进入路由之前执行getData() vm.getData(); }); }, //在路由离开前执行 beforeRouteLeave: (to, from, next) => { console.log('离开路由之前'); next(); },methods:{ getData:function () { this.axios({ method:'get', url:'http://localhost:8081/static/mock/data.json' }).then(function (response) { console.log(response) }) } } } </script>