zoukankan      html  css  js  c++  java
  • 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个,多了会报错

    人生到处知何似,应似飞鸿踏雪泥。
  • 相关阅读:
    02
    循环语句的注意点
    unsigned/signed int/char类型表示的数值范围
    C程序设计语言(第二版)--- 习题选
    第一篇来自博客园的博客--哈哈希望大家点赞
    脆弱的GPS系统--摘抄《环球科学》
    【Python入门自学笔记专辑】——函数式编程
    c++标准库conio.h文件
    推荐几个配色和图标网站
    Ajax实现简单下拉选项
  • 原文地址:https://www.cnblogs.com/lepanyou/p/15095328.html
Copyright © 2011-2022 走看看