VueX+VueRouter+Cookie实现简单登录页
路由页的登录导航守卫设置
1 import Cookies from 'js-cookie' 2 3 // Not login 4 router.beforeEach((to, from, next) => { 5 if (to.matched.some(m => m.meta.auth)) { 6 // 对路由进行验证 7 if (Cookies.get('userInfo')) { // 已经登陆 8 next() // 正常跳转到设置好的页面 9 } else { 10 // 未登录则跳转到登陆界面,query:{ Rurl: t o.fullPath} 11 // 表示把当前路由信息传递过去方便登录后跳转回来; 12 next({ path: '/login', query: { Rurl: to.fullPath } }) 13 } 14 } else { next() } 15 })
引入js-cookie
npm i js-cookie
模块化开发时:
import Cookies from 'js-cookie'
VueX中的设置
import Vue from 'vue'
import Vuex from 'vuex'
import Cookies from 'js-cookie'
Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    userInfo:  Cookies.get('userInfo'),
    isLogin: 0,
    currentUser: ''
  },
  mutations: {
    loginSuc(state,data){
      state.userInfo=data
//缓存2小时,1msx1000=1s,1sx60=1min,1minx60x2=2hours
      var date = new Date((new Date().getTime()+120*60*1000))
      Cookies.set('userInfo',data,{expires:date})
    },
    loginOut(state) {
      state.userInfo = null
      Cookies.remove('userInfo');
    }
  }
})
export default store
登录页登录逻辑部分
    handleLogin() {
      var name = this.loginForm.username;
      this.$message({
        message: "欢迎 " + name + ",(*^_^*)",
        center: true,
      });
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.userInfo.name = name;
          this.userInfo.isLogin = "100";
          this.$store.commit("loginSuc", this.userInfo);
          const url = this.$route.query.Rurl || "/";
          this.$router.push(url);
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
注:commit提交到store里一次最多提交2个,多了会报错
    人生到处知何似,应似飞鸿踏雪泥。
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号