Vue.js--导航守卫
导航守卫
- vue-router提供的导航守卫主要用来监听路由的进入和离开的。
- vue-router提供了beforeEach和afterEach,他们会在路由即将改变和改变前后触发。
示例
在路由跳转的同时,修改页面标题。
//引入Vue
import Vue from 'vue'
//引入vue-router
import VueRouter from 'vue-router'
//加载路由插件
Vue.use(VueRouter)
//创建一个数组来指定路由匹配列表,每一个路由映射一个组件
const routes = [
{
path: '/index',
//这种写法webpack会把每一个路由打包成一个js文件,实现懒加载也防止main.js文件过大
component: () => import('../components/index.vue'),
meta: {
title: '首页'
}
},
{
path: '/about',
component: () => import('../components/about.vue'),
meta: {
title: '关于'
}
},
{
path: '/user/:id',
component: () => import('../components/user.vue'),
meta: {
title: '个人主页'
}
}
]
//创建路由对象
const router = new VueRouter({
//使用HTML5的history模式
mode: 'history',
routes
})
//通过导航钩子设置导航守卫
router.beforeEach((to, from, next) => {
next()
document.title = to.meta.title;
})
//将router对象导出
export default router
导航钩子有3个参数:
- to:即将要进入的目标的路由对象;
- from:当前导航即将要离开的路由对象;
- next:调用该方法后,才能进入下一个钩子;
路由列表的meta字段可以自定义一些信息,beforeEach钩子可以从路由对象to里获取meta信息,从而改变标题。
next()方法可以设置参数,当参数为false时,可以取消导航;参数也可以是一个路径,使路由跳转到指定页面。
运行项目:
点击标签,标题随路由的跳转切换:
还没有评论,来说两句吧...