rounter分三种钩子:
1>全局钩子
1.1》beforeEach
1.2》afterEach
这两个钩子可以在独立js定义,然后在main.js用import导入即可。在路由内容有变化时候都会调用
其中
to : 表示目的页面
from: 表示离开的页面
next:是链条对象,返回给接下来的处理。结尾都要带上
//独立js文件,myrounter.js
import router from './router' import store from './store' import { getCookie } from '@/utils/auth' // 验权 router.beforeEach((to, from, next) => { NProgress.start() const cookieInfo = getCookie() console.log('cookieInfo', cookieInfo) if (getCookie()) { if (to.path === '/login') { next({ path: '/' }) } else { // console.log(store.getters) if (cookieInfo.length === 0 && to.path !== '/login') { next({ path: '/login' }) } else if (window.localStorage.getItem("is_need_examine")==1 && to.path !== '/answer'){ next({path:'/answer'}); }else{ next() } } } else { if (whiteList.indexOf(to.path) !== -1) { next() } else { next('/login') } } }) router.afterEach(() => { })
2>路由独享钩子
1.1》beforeEnter
在定义路由map时候定义
export const constantRouterMap = [ { path: '/', component: () => import('@/views/layouts/index'), redirect: '/home', meta: { title: '首页', keepAlive: false }, children: [ { path: '/home', name: 'Home', component: () => import('@/views/home/index'), meta: { title: '首页', keepAlive: true }, beforeEnter:(to, from ,next)=>{ } }, ] }, } ]
3》组件局部钩子
1.1》beforeRouteEnter
还未创建,this不可用
1.2》beforeRouteUpdate
1.3》beforeRouteLeave
在vue页面中定义
<!-- home --> <template> <div class="home-container"> </div> </template> <script> import keepAliveMixin from '../mixin/keepAlive' export default { name: "home", mixins: [keepAliveMixin], data() { return { //数据列表 list:[], //下拉刷新 refreshing:false, //上拉加载更多 loading:false, finished:false, // info:"", } }, computed: {}, destroyed() { console.log('destroyed'); }, mounted() { console.log('mounted'); }, beforeRouteEnter(){
next (vm => { // 这里通过 vm 来访问组件实例,解决了没有 this 的问题 })
},
beforeRouteUpdate(){
},
beforeRouteLeave(){
},
methods: { btnClick(){ ajaxTest(); }, } }
</script>
最后是完整的导航解析流程:
1.导航被触发
2.在失活的组件里调用离开守卫
3.调用全局的 beforeEach 守卫
4.在重用的组件里调用 beforeRouteUpdate 守卫
5.在路由配置里调用 beforEnter
6.解析异步路由组件
7.在被激活的组件里调用 beforeRouteEnter
8.调用全局的 beforeResolve 守卫
9.导航被确认
10.调用全局的 afterEach 钩子
11.触发 DOM 更新
12.在创建好的实例调用 beforeRouteEnter 守卫中传给 next 的回调函数