用vue-router来控制用户登录权限的原理,实际上就是应用了vue-router提供的router.beforeEach来注册一个全局钩子。具体用法
根据判断是否具有登录权限来设置路由跳转,如果没有全选统一跳转到登录页面。
第一步:新建一个名字为permission的js文件,代码如下
import router from './router'import NProgress from 'nprogress' // Progress 进度条import 'nprogress/nprogress.css'// Progress 进度条样式router.beforeEach((to, from, next) => {NProgress.start(); // 开启Progressif (sessionStorage.getItem('accessToken')) {next()} else {if (to.path ==="/login"|| to.path ==='/register'){next()}else {next('/login')}NProgress.done()}});router.afterEach(() => {NProgress.done() // 结束Progress});
在mian.js中导入permission.js,代码如下:
import './permission' // 权限
原文:/shirukai/article/details/80781586?utm_source=copy 版
首先需要新建一个store文件夹,新建index.js 、
main.js中引入store
将状态信息保存至localStorage中
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const key = 'user'
const isLogin = 'isLogin'
const store = new Vuex.Store({
state () {
return {
user: null,
isLogin: '0'
}
},
getters: {
getStorage: function (state) {
if (!state.user) {
state.user = JSON.parse(localStorage.getItem(key))
state.isLogin = localStorage.getItem(isLogin)
}
return state.user
}
},
mutations: {
$_setLogin (state, value) {
state.isLogin = value
localStorage.setItem(isLogin, value)
},
$_setStorage (state, value) {
state.user = value
localStorage.setItem(key, JSON.stringify(value))
},
$_removeStorage (state) {
state.user = null
localStorage.removeItem(key)
}
}
})
export default store
然后在main.js
router.beforeEach((to, from, next) => {
if (to.matched.some(m => m.meta.auth)) {
if (window.localStorage.isLogin === '1') {
next()
} else if (to.path !== '/') {
next({path: '/login'})
Vue.prototype.$message.warning('检测到您还未登录,请登录后操作!')
}
} else {
next()
}
})
在组件中表单验证成功后,点击按钮时:
this.$message({
message: '登录成功',
type: 'success'
})
this.$mit('$_setStorage', {user: this.loginForm.username})
this.$mit('$_setLogin', '1')
this.$router.push({name: 'Home'})
前提是需要在router中添加meta: {auth: true}
{
path: '/',
component: Login,
name: 'Login',
meta: {auth: true}
},
原文:/qq_32917123/article/details/80898439?utm_source=copy
如果觉得《如何在vue中判断用户是否登录 登录权限》对你有帮助,请点赞、收藏,并留下你的观点哦!