//原文来自https://segmentfault.com/a/1190000016040068
//设置路由守卫
---main.js:
router.beforeEach((to, from, next) => {
let getFlag = sessionStorage.getItem("Flag");
//如果登录标志存在且为isLogin,即用户已登录
if (getFlag === "isLogin") {
//设置vuex登录状态为已登录
store.state.isLogin = true
next()
//如果已登录,还想想进入登录注册界面,则定向回首页
if (!to.meta.isLogin) {
next({
path: '/admin'//首页的path路径
})
}
//如果登录标志不存在,即未登录
} else {
//用户想进入需要登录的页面,则定向回登录界面
if (to.meta.isLogin) {
next({
path: '/login',//登录页的path路径
})
//用户进入无需登录的界面,则跳转继续
} else {
next()
}
}
})
---router---index.js:
//登录页
meta: {
isLogin: false
}
//首页
meta: {
isLogin: true
}
---登录页.vue的登录方法:
//请求登录的方法名:login
login(){
this.axios.请求方式("接口",{请求参数}).then(res=>{
//登录成功之后
this.$store.dispatch("userLogin", true);
sessionStorage.setItem("Flag", "isLogin");//设置登录状态
})
}
---store.js
const store = new Vuex.Store({
state: {
isLogin: false,
},
getters: {
//获取登录状态
isLogin: state => state.isLogin,
},
actions: {
//获取登录状态
userLogin({
commit
}, flag) {
commit("userIsLogin", flag)
},
},
mutations: {
userIsLogin(state, aisLogin) {
state.isLogin = aisLogin;
},
}
})
以下是我自己项目里用到的。
/router/index.js
{
path: '/',
redirect: {
name: 'login'
},
},
{
path: '/login',
name: 'login',
component: resolve => require(['@/view/login/login'], resolve),
meta: {
isLogin: false
}
},
{
path: '/admin',
name: 'admin',
component: resolve => require(['@/view/index/admin'], resolve),
meta: {
isLogin: true
}
},
/main.js
//如果后台是根据cookie判断的话要加这一条
//axios.defaults.withCredentials = true;//让axios请求留下cookie,默认是不会有的
router.beforeEach((to, from, next) => {
let getFlag = sessionStorage.getItem("Flag");
if (getFlag === "isLogin") {
store.state.isLogin = true
next()
if (!to.meta.isLogin) {
next({
path: '/admin'
})
}
} else {
if (to.meta.isLogin) {
next({
path: '/login',
})
} else {
next()
}
}
})
/login/login.vue
--- html
<ul>
<li>
<span class="iconfont iconyonghu"></span>
<input v-model="account" placeholder="用户名" type="text">
</li>
<li>
<span class="iconfont iconmima"></span>
<input v-model="password" placeholder="密码" type="password">
</li>
</ul>
<button class="login-button" @click="Login">登录</button>
---script
data:
account:'',//123456
password:'',//123456
methods:
Login(){
let account = this.account;
let password = this.$md5(this.password) ;//$md5 npm下的加密组件
// let password = this.password;
console.log("password",password)
this.$http.post(this.$api+"/manage/manageLogin",{account,password}).then(res=>{
console.log(res)
let _res = res.data
let code = res.data.code
let msg = res.data.msg
console.log(code)
if(code != 200){
this.$message.error(msg)
}else{
this.$store.dispatch("userLogin", true);
sessionStorage.setItem("Flag", "isLogin");//设置登录状态
this.$router.push({name:'admin'})
this.$message("登录成功")
}
}).catch(e=>{
this.$message.error(e)
})
}
/modules/store.js
state: {
isLogin: false,
},
getters: {
//获取登录状态
isLogin: state => state.isLogin,
},
actions: {
//获取登录状态
userLogin({
commit
}, flag) {
commit("userIsLogin", flag)
},
},
mutations: {
userIsLogin(state, aisLogin) {
state.isLogin = aisLogin;
},
}