Vue中的路由配置常用属性
router:路由
页面跳转的核心库;
引入路由:import VueRouter from 'vue-router';
注册路由:const router = new VueRouter({
})
mode:模式
路由有hash history两种模式:
hash模式URL中包含#,#后边是路径名称;
const router = new VueRouter({
mode: 'hash',
})
history模式URL中不包含#,域名后边直接就是路径名称;
const router = new VueRouter({
mode: 'history',
})
base:基路径
默认是“/”,当设置基路径的时候,访问http://localhost:8080/和访问http://localhost:8080/home是一样的
const router = new VueRouter({
base: '/home',
})
routes:路径集合
给每个页面配置指定路径信息,通过匹配路径信息跳转到指定页面,数据结构为数组结构;
const router = new VueRouter({
routes:[
{
path:'/home',
name:'Home',
component: () => import('../View/home'),
children:[
]
}
]
})
path: 路径
路由会根据URL中的路径进行匹配path,匹配通过会跳转到相对应组件页面;
const router = new VueRouter({
routes:[
{
path:'/home', //路径
name:'Home',
component: () => import('../View/home'),
children:[
]
}
]
})
name:名称
路由跳转也可以根据指定name名称跳转到匹配组件页面;
const router = new VueRouter({
routes:[
{
path:'/home',
name:'Home', //name名称
component: () => import('../View/home'),
children:[
]
}
]
}
redirect:重定向
可以通过重定向,跳转到指定的页面组件;
const router = new VueRouter({
routes:[
{
path:'/',
redirect:'home' //重定向
},
{
path:'/home',
name:'Home',
component: () => import('../View/home'),
children:[
]
}
]
}
component:组件
为当前路径配置相对应的组件,匹配path或name成功后,获取当前配置的组件渲染到页面
const router = new VueRouter({
routes:[
{
path:'/home',
name:'Home',
component: () => import('../View/home'),
children:[
]
}
]
}
meta:路由元信息
可以在此属性内配置信息或参数,可能是否拦截路由或者组件需要的信息都可以配置;
const router = new VueRouter({
routes:[
{
path:'/home',
name:'Home',
component: () => import('../View/home'),
meta: {
title: '首页',
is_active: true
},
children:[
]
}
]
}
children:子路由
可能当前组件需要展示多个子组件,通过不同的事件展示对应的子组件;可以使用children来进行配置;
注意:子组件中的path不要以“/”开头,直接配置路径地址就可以;
const router = new VueRouter({
routes:[
{
path:'/home',
name:'Home',
component: () => import('../View/home'),
meta: {
title: '首页',
is_active: true
},
children:[
{
path:'new',
name:'New',
component: () => import('../View/home'),
}
]
}
]
}
befoerEach:路由切换之前(路由守卫,路由卫士)
一般做后台管理平台的可能需要做些判断,判断用户权限或者是否登陆等信息;
有三个参数:
to:要切换到那个页面的路径信息
from:现在在那个页面的路径信息
next:下一步事件,befoerEach方法中必须指向next()事件,否则无法切换路径;
router.beforeEach(function (to, from, next) {
//可以在此做些判断是否指向next()
next()
})
next:放行通过
在befoerEach方法中使用:一般用于判断是否要切换路由;
router.beforeEach(function (to, from, next) {
//可以在此做些判断是否指向next()
if(to.name == 'Home'){
next()
}
})
afterEach:路由切换之后(路由守卫,路由卫士)
在路由切换完成后执行,可以在此方法中设置页面的title,或这一些其它操作;
有两个参数:
to:要切换到那个页面的路径信息
from:现在在那个页面的路径信息
router.afterEach((to,from)=>{
if (to.meta.title){
document.title = to.meta.title;
}else {
document.title = "敲代码的猪"
}
});
关注收藏不迷失,后续vue-router如何使用会全面整理后再发小文章;