vue导航守卫如何运用
每个守卫方法接收三个参数:
to: 即将要进入的目标 路由对象
from:当前导航正要离开的路由
next:: 放行
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="../node_modules/vue/dist/vue.js"></script>
<script src="../node_modules/vue-router/dist/vue-router.js"></script>
</head>
<body>
<div id="app">
<router-link to="/home">首页</router-link>
<router-link to="/blog">我的博客</router-link>
<router-link to="/login" >登录</router-link>
<a href="javascript:void(0)" @click="clearOut">退出</a>
<router-view></router-view>
</div>
<script>
//声明组件
var Home={
template:`
<div>我是首页</div>
`
}
var Blog={
template:`
<div>我是博客</div>
`
}
var Login={
data(){
return{
uname:'',
psw:''
}
},
template:`
<div>
<input type="text" v-model="uname"/>admin
<input type="text" v-model="psw"/>密码
<input type="button" @click="handlerLogin" value="登录">
</div>
`,
methods:{
handlerLogin(){
<!-- //保存用户名和密码 本地保存 -->
localStorage.setItem("username",{name:this.uname,psw:this.psw});
<!-- //编程式导航 -->
this.$router.push({
path:'/blog'
})
}
}
}
var router=new VueRouter({
routes:[
{
path:'/home',
component:Home
},
{
path:'/blog',
component:Blog,
<!-- 想在哪个组件做控制,跳转之前做配置 -->
meta:{
//用户访问该组件是否需要登录
auth:true
}
},
{
path:'/login',
component:Login
},
]
})
router.beforeEach((to,from,next)=>{
console.log(to,from);
if(to.meta.auth){
<!-- //判断有没有用户名和密码 -->
if(localStorage.getItem("username")){
<!-- //有用户名说明已经登录 -->
<!-- 放行 -->
next()
}else{
<!-- //没有登录,渲染登录组件 -->
next({
path:"/login"
})
}
}else{
next()
}
})
//router挂载到实例上
new Vue({
el:"#app",
router,
methods:{
clearOut(){
localStorage.removeItem("username");
this.$router.push({
path:'/login'
})
}
}
})
</script>
</body>
</html>