mode:设置路由模式
import VueRouter from 'vue-router';
import Home from '../components/Home.vue';
import About from '../components/About.vue';
export default new VueRouter({
//路由工作的两种模式 默认是hash模式 mode改变模式为history模式
mode: 'history',
routes: [
{
path: '/home',
component: Home,
children: [
//不需要写父路径 以及 / 也可以给路由命名 跳转时可以不用path 使用name即可
{ path: 'news', component: News,name:'news',
children: [
{
name: 'detail',
//路由使用parmas传参,跳转必须使用name不可以使用path 获取使用$route.params.id获取
path: 'detail/:id',
component: Detail,
//给details组件传递对象,所有数据在details中可以以props的方式接收
// props:{a:1,b:2}
//如果props是true,则路由收到的params参数会以props的形式传递 即 id 会以props方式传递
// props:true
// 如果props是函数,则路由同样以props的形式传递参数给组件,但是这可以通过route结构获取到query并传参(此处使用解构赋值的连续写法 先从route中结构获取query,再从query中结构出id,title
props({query:{id,title}}){ return {id,title} }
}
]
},
{ path: 'messages', component: Message }
]
},
{
path: '/about',
component: About
}
]
});
keep-alive标签
可以使用keep-alive标签包含用来缓存路由组件,默认情况下缓存所有组件,可以使用:include="[‘组件名’]" 指定需要缓存的路由组件。exclude功能刚好相反
在使用keep-alive包含路由组件后,组件不会触发beforeDestory销魂流程,需要使用activated激活,deactivated()失活。
路由守卫
router.beforeEach((to, from, next) => {
if (to.meta.isAuth) {
//判断权限
if (localStorage.getItem('token') === 'user')
//继续路由跳转
next();
else alert('undefind token');
} else next()//取消跳转;
});
router.afterEach((to, from) => {
// 路由跳转完成后的操作
});
{
path: '/mine',
component: MyComponent,
beforeEnter: (to, from, next) => {
// 路由独享守卫逻辑
}
}
export default {
beforeRouteEnter (to, from, next) {
// 在渲染该组件的对应路由被确定前调用
next();
},
beforeRouteUpdate (to, from, next) {
// 当前路由改变,但是该组件被复用时调用
next();
},
beforeRouteLeave (to, from, next) {
// 导航离开该组件的对应路由时调用
next();
}
}