vue2+vuex登录功能

登录功能

1.阅读接口文档,封装登录接口

2.登录前的校验(手机号,图形验证码,短信验证码)

3.调用方法,发送请求,成功添加提示并跳转

封装登录接口

js 复制代码
// 登录
export const codeLogin = (mobile, smsCode) => {
  return request.post('/passport/login', {
    form: {
      isParty: false, // 是否第三方登录
      partyData: {}, // 第三方登录信息
      mobile, // 手机号
      smsCode // 短信验证码
    }
  })
}

登录逻辑

js 复制代码
async login() {
      // 校验
      if (!this.vaildFn()) return
      if (!this.timer) {
        this.$toast('请先获取短信验证码')
        return
      }
      if (!this.msgCode) {
        this.$toast('请输入短信验证码')
        return
      }
      if (!/^\d{6}/.test(this.msgCode)) {
        this.$toast('短信验证码格式不正确')
        return
      }
      const res = await codeLogin(this.mobile, this.msgCode)
      this.$store.commit('user/setUserInfo', res.data)
      // 登录成功后清理倒计时
      this.clearCountdown()
      // 登录
      this.$toast('恭喜登录成功')
      this.$router.push('/')
    }

响应拦截器统一处理错误

js 复制代码
import axios from 'axios'
import { Toast } from 'vant'
const instance = axios.create({
  baseURL: 'https://smart-shop.itheima.net/index.php?s=/api/',
  timeout: 5000
})

axios.interceptors.request.use(
  function (config) {
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  function (response) {
    const res = response.data
    if (res.status !== 200) {
      Toast(res.message)
      return Promise.reject(res.message)
    }
    return res
  },
  function (error) {
    return Promise.reject(error)
  }
)

export default instance

登录权证信息存储

js 复制代码
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {},
  getters: {},
  mutations: {},
  actions: {},
  modules: {
    user
  }
})

src\store\modules\user.js

js 复制代码
export default {
  namespaced: true,
  state() {
    return {
      // 个人权证相关
      userInfo: {
        token: '',
        userId: ''
      }
    }
  },
  mutations: {},
  actions: {},
  getters: {}
}
js 复制代码
async login() {
      // 校验
      if (!this.vaildFn()) return
      if (!this.timer) {
        this.$toast('请先获取短信验证码')
        return
      }
      if (!this.msgCode) {
        this.$toast('请输入短信验证码')
        return
      }
      if (!/^\d{6}/.test(this.msgCode)) {
        this.$toast('短信验证码格式不正确')
        return
      }
      const res = await codeLogin(this.mobile, this.msgCode)
      this.$store.commit('user/setUserInfo', res.data)
      // 登录成功后清理倒计时
      this.clearCountdown()
      // 登录
      this.$toast('恭喜登录成功')
      this.$router.push('/')
    }

storage存储模块-vuex持久化处理

js 复制代码
const INFO_KEY = 'hm_shopping_info'
export const getInfo = () => {
  const defaultObj = {
    token: '',
    userId: ''
  }
  const result = window.localStorage.getItem(INFO_KEY)
  return result ? JSON.parse(result) : defaultObj
}

export const setInfo = (obj) => {
  window.localStorage.setItem(INFO_KEY, JSON.stringify(obj))
}

export const removeInfo = () => {
  window.localStorage.removeItem(INFO_KEY)
}

添加请求loading效果

js 复制代码
import axios from 'axios'
import { Toast } from 'vant'
const instance = axios.create({
  baseURL: 'https://smart-shop.itheima.net/index.php?s=/api/',
  timeout: 5000
})

instance.interceptors.request.use(
  function (config) {
    Toast.loading({
      forbidClick: true, // 禁止背景点击
      message: '加载中...',
      loadingType: 'spinner', // 加载图标
      duration: 0 // 不会自动消息
    })
    return config
  },
  function (error) {
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  function (response) {
    const res = response.data
    if (res.status !== 200) {
      Toast(res.message)
      return Promise.reject(res.message)
    }
    Toast.clear()
    return res
  },
  function (error) {
    return Promise.reject(error)
  }
)

export default instance

页面访问拦截

js 复制代码
const authUrls = ['/pay', '/myorder']

// 全局前置导航守卫
router.beforeEach((to, from, next) => {
  // 非权限页面
  if (!authUrls.includes(to.path)) {
    next()
    return
  }
  // 需要权限的页面
  const token = store.getters.token
  if (!token) {
    next('/login')
    return
  }
  next()
})
js 复制代码
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {},
  getters: {
    token(state) {
      return state.user.userInfo.token
    }
  },
  mutations: {},
  actions: {},
  modules: {
    user
  }
})
相关推荐
谙忆10241 天前
图像任务超时怎么重试:先分执行状态,再做结果验收
javascript
@大迁世界1 天前
Firefox 本地模式:localhost 再见了 ?
前端·架构
米米商聊1 天前
同名附件为什么被 Map 覆盖?重复键与一对多索引
前端·javascript
echome8881 天前
Python 异常处理:try、else、finally 的正确搭配
开发语言·前端·python·异常处理·编程技巧
时间的情敌1 天前
OpenLayers 实战|Vue3 + OpenLayers 完整工程案例(加载天地图、要素、弹窗、绘制、WFS)
前端·openlayers
陈随易1 天前
下载神器!Motrix 停更三年后重写回归
前端·后端·程序员
前端的日常1 天前
一个人+AI做情侣食谱小程序,0 费用的服务器
前端·后端
计算机魔术师1 天前
谷歌搜索广告踩刹车,AI广告成为救命稻草
前端
总要学点什么1 天前
第81篇:数据可视化-PM2.5分布——让圆点的胖瘦替每座城市报出浓度
前端·信息可视化·echarts·cesium·空间分析
IT_陈寒1 天前
Vue的v-for里用了个临时变量,页面直接挂了
前端·人工智能·后端