操作:
是时机函数,在页面加载前,可以在这两个函数里面做一些事情,
比如发送异步请求。
类似过滤器,或者拦截器。
1. axios安装
安装报错,多装几遍,或者用cnpm安装
npm install axios -s
npm install --save vue-axios
2. 参数说明
// 两个钩子函数 过滤器 || 拦截器的环绕
// to 路由将要跳转的路径信息
// from 路径跳转前的路径信息
// next 路由的控制参数
// next() 跳入下一个页面
// next('/path') 改变路由的跳转方向,跳到下一个页面
// next(false) 返回原来的页面
// next((vm) => {}) 尽在beforeRouteEnter 中可用,vm是组件实例
beforeRouteEnter: (to, from, next) => {console.log('进入路由之前');next() // 必写
},
beforeRouteLeave: (to, from, next) => {console.log('进入路由之后')next()
}
3. demo
<template><div>{{ info[1].hobby[0] }}{{ info[0].home }}</div>
</template><script>export default {beforeRouteEnter: (to, from, next) => {console.log('进入路由前..')next((vm => {vm.getData()})) // 发送异步请求并放行},beforeRouteLeave: (to, from, next) => {console.log('进入路由后..')next()},data() {return ({info: [{name: null,home: null},{hobby: [null, null]}]})},methods: {getData: function() {/* ../../static/mock/data.json */this.axios.get('../../static/mock/data.json').then(response => (this.info = response.data))}}}
</script><style scoped></style>