2021-02-01 09:49发布
在实际项目中,路由跳转前做一些验证,比如登录验证,是网站中的普遍需求。举个例子,我们通常使用 router.beforeEach 注册一个全局前置守卫用来判断登录的状态:
router.beforeEach
let
routesArr = [{
path:
'/home'
,
name:
"home"
//redirect:"/about",//重定向
//alias: '/index',//别名
component: {
template: ` 这是首页 `
这是首页
}
}, {
'/about'
'about'
template: ` 这是关于我们页 `
这是关于我们页
'/user/:name'
// :name的作用是动态访问一个地址,比如传进来的是张三,就显示张三的信息
'user'
// 这个name的作用是配合第95行添加属性用的,二者必须一致
template: ` 我叫:{{ $route.params.name }} 我今年:{{ $route.query.age }} 岁了 "more" append> 更多信息 `
我叫:{{ $route.params.name }}
我今年:{{ $route.query.age }} 岁了
"more" append> 更多信息
"more"
append> 更多信息
},
children: [{
'more'
template: `
用户:{{ $route.params.name }} 的详细信息 abcd1234 `
用户:{{ $route.params.name }} 的详细信息 abcd1234
}]
];
const vRouter =
new
VueRouter({
routes: routesArr
// 这里要写routes ,而不是routers,不然 没数据
})
vRouter.beforeEach((to, from, next) => {
//这里写你的判断逻辑
const nextRoute = [
'home'
'good-list'
'good-detail'
'cart'
'profile'
//需要登陆的页面名
isLogin= localEvent.get(
'web_login'
)||
false
;
//获取是否登录状态
// 未登录状态;当路由到nextRoute指定页时,跳转至login
if
(nextRoute.indexOf(to.name) > -1) {
(!isLogin) {
//router.push({ name: 'login' });//可以直接跳转名
//next({ path: '/login', query: { redirect: to.fullPath } });//也可以跳转路径,并带上重定向
// 已登录状态;当路由到login时,跳转至home
(to.name ===
'login'
) {
(isLogin) {
router.push({ name:
});
next();
最多设置5个标签!
在实际项目中,路由跳转前做一些验证,比如登录验证,是网站中的普遍需求。举个例子,我们通常使用
router.beforeEach
注册一个全局前置守卫用来判断登录的状态:let
routesArr = [{
path:
'/home'
,
name:
"home"
,
//redirect:"/about",//重定向
//alias: '/index',//别名
component: {
template: `
`
这是首页
}
}, {
path:
'/about'
,
name:
'about'
,
component: {
template: `
`
这是关于我们页
}
}, {
path:
'/user/:name'
,
// :name的作用是动态访问一个地址,比如传进来的是张三,就显示张三的信息
name:
'user'
,
// 这个name的作用是配合第95行添加属性用的,二者必须一致
component: {
template: `
`
我叫:{{ $route.params.name }}
我今年:{{ $route.query.age }} 岁了
"more"
append> 更多信息
},
children: [{
path:
'more'
,
component: {
template: `
用户:{{ $route.params.name }} 的详细信息 abcd1234
}
}]
}
];
const vRouter =
new
VueRouter({
routes: routesArr
// 这里要写routes ,而不是routers,不然 没数据
})
vRouter.beforeEach((to, from, next) => {
//这里写你的判断逻辑
const nextRoute = [
'home'
,
'good-list'
,
'good-detail'
,
'cart'
,
'profile'
];
//需要登陆的页面名
let
isLogin= localEvent.get(
'web_login'
)||
false
;
//获取是否登录状态
// 未登录状态;当路由到nextRoute指定页时,跳转至login
if
(nextRoute.indexOf(to.name) > -1) {
if
(!isLogin) {
//router.push({ name: 'login' });//可以直接跳转名
//next({ path: '/login', query: { redirect: to.fullPath } });//也可以跳转路径,并带上重定向
}
}
// 已登录状态;当路由到login时,跳转至home
if
(to.name ===
'login'
) {
if
(isLogin) {
router.push({ name:
'home'
});
}
}
next();
});
一周热门 更多>