JavaScript

超轻量级php框架startmvc

vuex实现登录状态的存储,未登录状态不允许浏览的方法

更新时间:2020-07-01 19:36 作者:startmvc
基础思路就是使用vuex状态管理来存储登录状态(其实就是存一个值,例如token),然后在路由

基础思路就是使用vuex状态管理来存储登录状态(其实就是存一个值,例如token),然后在路由跳转前进行登录状态的判断,可以使用vue-router的全局前置守卫beforeEach,也可以使用路由独享的守卫beforeEnter。

导航守卫

正如其名,vue-router``` 提供的导航守卫主要用来通过跳转或取消的方式守卫导航。有多种机会植入路由导航过程中:全局的, 单个路由独享的, 或者组件级的。 记住参数或查询的改变并不会触发进入/离开的导航守卫。你可以通过观察 $route 对象来应对这些变化,或使用beforeRouteUpdate的组件内守卫。

完整的导航解析流程

1、导航被触发。

2、在失活的组件里调用离开守卫。

3、调用全局的 beforeEach 守卫。

4、在重用的组件里调用 beforeRouteUpdate 守卫 (2.2+)。

5、在路由配置里调用 beforeEnter。

6、解析异步路由组件。

7、在被激活的组件里调用 beforeRouteEnter。

8、调用全局的 beforeResolve 守卫 (2.5+)。

9、导航被确认。

10、调用全局的 afterEach 钩子。

11、触发 DOM 更新。

12、用创建好的实例调用 beforeRouteEnter 守卫中传给 next 的回调函数。

全局守卫

你可以使用 router.beforeEach注册一个全局前置守卫


const router = new VueRouter({ ... })
router.beforeEach((to, from, next) => {
 // ...
})

当一个导航触发时,全局前置守卫按照创建顺序调用。守卫是异步解析执行,此时导航在所有守卫 resolve 完之前一直处于 等待中。

每个守卫方法接收三个参数:

to: Route:即将要进入的目标 路由对象

from: Route:当前导航正要离开的路由

next: Function:一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。

next():进行管道中的下一个钩子。如果全部钩子执行完了,则导航的状态就是 confirmed (确认的)。

next(false):中断当前的导航。如果浏览器的 URL 改变了(可能是用户手动或者浏览器后退按钮),那么 URL 地址会重置到 from 路由对应的地址。

next('/')或者next({ path: '/' }): 跳转到一个不同的地址。当前的导航被中断,然后进行一个新的导航。

next(error):(2.4.0+) 如果传入 next 的参数是一个 Error 实例,则导航会被终止且该错误会被传递给 router.onError()注册过的回调。

确保要调用 next 方法,否则钩子就不会被 resolved。

路由独享的守卫

你可以在路由配置上直接定义beforeEnter守卫:


const router = new VueRouter({
 routes: [
 {
 path: '/foo',
 component: Foo,
 beforeEnter: (to, from, next) => {
 // ...
 }
 }
 ]
})

还有其他部分守卫,详情可以看官方文档https://router.vuejs.org/zh-cn/advanced/navigation-guards.html

安装vuex后

创建store.js


import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const state = {
 isLogin: 0
}
const mutations = {
 changeLogin(state,status){
 state.isLogin = status;
 }
}
const actions = {
 loginAction({commit}){
 commit('changeLogin',1);
 }
}
export default new Vuex.Store({
 state,
 actions,
 mutations
})

login.vue中

引入import { mapActions,mapState } from 'vuex'

接着进行登录状态的改变,base_url就是路径


export default {
 name: 'Login',
 data(){
 return{
 loginForm: {
 username: '',
 password: '',
 },
 rules: {
 username: [
 { required: true, message: '请输入用户名', trigger: 'blur' },
 ],
 password: [
 { required: true, message: '请输入密码', trigger: 'blur' }
 ],
 },
 showLogin: false
 }
 },
 mounted(){
 this.showLogin = true;
 },
 computed: {
 ...mapState(['isLogin'])
 },
 methods: {
 ...mapActions(['loginAction']),
 submitForm(formName){
 this.$refs[formName].validate((valid) => {
 if(valid){
 if(this.loginForm.username == 'aaa' && this.loginForm.password == '111'){
 console.log('验证通过');
 this.loginAction();
 this.$router.push('manage');
 }else{
 console.log('账号密码出错');
 // this.$message.error('账号密码出错');
 this.$message({
 type: 'error',
 message: '账号密码出错'
 });
 }
 console.log('请求地址: ' + base_url);
 }else{
 console.log('验证失败');
 return false;
 }
 })
 }
 }
 }

接下去只要使用路由守卫即可

beforeEach使用实例


router.beforeEach((to,from,next)=>{
 if(to.meta.check){
 var check = async function(){
 const result = await checkUser();
 if(result.status == 0){
 next();
 }else{
 alert('用户未登录');
 next({path: '/login'});
 }
 }
 check(); //后台验证session
 }else{
 next();
 }
})

beforeEnter使用实例


export default new Router({
 routes: [
 {
 path: '/login',
 component: Login
 },
 {
 path: '/manage',
 name: '',
 component: Manage,
 beforeEnter: (to,from,next)=> { //导航守卫
 console.log(to)
 console.log(from)
 if(store.state.isLogin == 1){
 console.log('用户已经登录');
 next();
 }else{
 console.log('用户未登录');
 next({path: '/login',query:{ Rurl: to.fullPath}}); //未登录则跳转到登陆界面,query:{ Rurl: to.fullPath}表示把当前路由信息传递过去方便登录后跳转回来
 }
 } 
 }
 ]
})

以上这篇vuex实现登录状态的存储,未登录状态不允许浏览的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持脚本之家。