定义
路由meta原数据->meta是对于路由规则是否需要验证权限的配置
路由对象中和name属性同级{meta:{isChecked:true}}
{name:'music',path:'/music', component:Music,meta:{isChecked:true}}
路由钩子->权限控制的函数执行时期
每次路由匹配后,渲染组件到router-view之前
router.beforeEach(function(to,from,next){ })
router.beforeEach(function(to,from,next){
if(!to.meta.isChecked){
next(); //不调用next 就会卡住
}else{ // 音乐界面如果登录了就继续,没登录就提示先登录
if(isLogin){
next(); //不传值叫放行
// next(false) // 取消用户导航行为
}else{
alert('请先登录。。。')
next({name:'login'}) // 重定向 /login
}
}
})
demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script src='../node_modules/vue/dist/vue.js'></script>
<!-- 1、引入vue-router -->
<script src="vue-router.js"></script>
</head>
<body>
<div id="app"></div>
<script>
let isLogin = false;
var Login = {
template:`
<div>我是登录界面</div>
`,
created() {
isLogin = true;
},
}
var Music = {
template:`
<div>我的音乐界面</div>
`
}
//2、安装插件
Vue.use(VueRouter);
// 3、创建一个路由对象
var router = new VueRouter();
// 可以多次追加路由规则,动态的获取路由规则
// 更为灵活,可以方便调用后追加路由规则
router.addRoutes([
// 默认首页路由 ***component注意不加s
{path:'/',redirect:{name:'login'}},
{name:'login',path:'/login', component:Login},
// meta:{isChecked:true} 给未来路由的权限控制,全局路由守卫来做参照条件
{name:'music',path:'/music', component:Music,meta:{isChecked:true}}
])
router.beforeEach(function(to,from,next){
console.log(to);
console.log(from);
// login 等放行
// if(to.name === 'login' || to.path == '/'){
// next(); //不调用next 就会卡住
// }else{ // 音乐界面如果登录了就继续,没登录就提示先登录
// if(isLogin){
// next(); //不传值叫放行
// // next(false) // 取消用户导航行为
// }else{
// alert('请先登录。。。')
// next({name:'login'}) // 重定向 /login
// }
// }
if(!to.meta.isChecked){
next(); //不调用next 就会卡住
}else{ // 音乐界面如果登录了就继续,没登录就提示先登录
if(isLogin){
next(); //不传值叫放行
// next(false) // 取消用户导航行为
}else{
alert('请先登录。。。')
next({name:'login'}) // 重定向 /login
}
}
})
// 6、指定路由改变局部的变量
var App = {
template:`
<div>
<router-link :to="{name:'login'}">登录</router-link>
<router-link :to="{name:'music'}">去听歌</router-link>
<router-view></router-view>
</div>
`
}
// 5、将配置好的路由对象关联值vue实例中
new Vue({
el:"#app",
router:router,
// 不加这一步,会导致运行时,undefined,对象中取不到matched
components:{
"app":App
},
template:`<app/>`
})
</script>
</body>
</html>