Vue学习笔记三:使用vuex与localstorage管理登录权限

使用vuex与localstorage管理登录权限

此次采用vuex + localstorage 配合使用来管理用户的登录状态,只使用vuex的话在用户进行刷新时将会自动删除,所以配合localstorage,这样可以让SPA应用中既可以同步用到数据,又不受刷新影响,实现步骤如下:

下载并安装vuex(具体可参见笔记一)
npm install vuex -S
在公用base.js中,设置localstorage方法,之后可以通过this.方法调用
Vue.prototype.setToken = function (tokenName, tokenValue) {
    if (window.localStorage) {
      localStorage.setItem(tokenName, tokenValue);
    } else {
      alert('This browser does NOT support localStorage');
    }
};
Vue.prototype.getToken = function (name) {
    var token = localStorage.getItem(name);
    if (token) {
      return token;
    } else {
      return '';
    }
  };
在store.js中定义登录状态
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
  // 定义状态
  state: {
    //登录状态,默认为'',当登录成功后自动再更新状态
    isLogin :'' 
  },
  mutations:{
    isLogin(state,msg){
      state.isLogin = msg;
      this.setToken('isLogin',msg)
    }
  }
})
export default store

在登录或者注册的登录成功时,改变isLogin状态

 codeLogin() {
      if (this.codePhone == '') {
        this.pupUp('手机号不能为空')
      } else if (!this.phoneReg.test(this.codePhone)) {
        this.pupUp('手机号码格式错误')
      } else if (this.code == '') {
        this.pupUp('请输入验证码')
      } else if (!this.codeReg.test(this.code)) {
        this.pupUp('验证码格式不正确')
      } else {
        this.axios
          .post('/api/v1/nopass_login', {
            mobile: this.codePhone,
            verfiycode: this.code,
            openid: this.openid,
            client: 'wechat'
          })
          .then(res => {
            console.log(res)
            if (res.data.code == 0) {
              this.setToken('bulaapi_token', res.data.data.token)
              this.setToken('userInfo', JSON.stringify(res.data.data.user))
              let userInfo = this.getToken('userInfo')
              userInfo = JSON.parse(userInfo)
              this.setToken('user_phone', userInfo.mobile)
              this.pupUp('登录成功')

              //设置本地存储及vuex仓库中islogin的状态值
              this.setToken('isLogin',100)
              this.$store.commit('isLogin',100)

              this.$router.push(this.$route.query.redirect)
            }
          }).catch(err=>{
            console.log(err)
          })
      }

在main.js中vue实例上进行判断

new Vue({
  el: '#app',
  router,
  store,
  components: {
    App
  },
  template: '<App/>',
  created(){
    //判断是否有本地存储中是否有isLogin,并更新vuex仓库
    if(this.getToken('isLogin') == null){
      this.setToken('isLogin','')
    }
    this.$store.state.isLogin = this.getToken('isLogin')
    console.log(this.$store.state.isLogin)
  }
})

在main.js中设置路由钩子函数,在跳转前进行判断

import router from './router';
Vue.use(router);

router.beforeEach((to, from, next) => {
//设置延时器让created先执行在进行路由跳转
  setTimeout((res) => {
  // 判断该路由是否需要登录权限
    if (to.meta.requireAuth) { 
    // 通过vuex state获取当前的状态是否存在
      if (store.state.isLogin) { 
        next();
      } else {
        next({
          path: '/login',
          query: {
            redirect: to.fullPath
          } // 将跳转的路由path作为参数,登录成功后跳转到该路由
        })
      }
    } else {
      next();
    }
  }, 100);

在路由的index.js中对需要验证的页面进行设置

routes: [{
      path: '/',
      name: 'My',
      component: My,
      meta: {
        requireAuth: true, // 添加该字段,表示进入这个路由是需要登录的
      },
    },
    ...
]

猜你喜欢

转载自blog.csdn.net/weixin_42018790/article/details/80744954