网络编程 发布日期:2024/11/10 浏览次数:1
1.安装Vuex
npm install vuex --save
2. 新建store目录结构
3. 编辑store.js
import Vuex from 'vuex' import Vue from 'vue' import defaultState from './state/state' import mutations from './mutations/mutations' import getters from './getters/getters' import actions from './actions/actions' Vue.use(Vuex) // 开发环境 const isDev = process.env.NODE_ENV === 'development' export default new Vuex.Store({ strict: isDev, // 开发环境中使用严格模式,防止给Vuex的状态对象直接赋值 state: defaultState, mutations, getters, actions })
4. 编辑state.js
export default { tokenStatus: true, // token状态 }
5. 编辑mutations.js
export default { updateTokenStatus (state, bool) { state.tokenStatus = bool } }
PS: getters用于计算属性,actions用于异步操作(暂无使用)
6. 挂载到vue根目录下,编辑main.js
import store from './store/store' new Vue({ store, router, render: h => h(App) }).$mount('#app')
7. login 登录时,改变state.tokenStatus的值
import { mapMutations } from 'vuex' methods: { // 声明Vuex的mutations的方法 ...mapMutations(['updateTokenStatus']), // 登录方法 login () { ...... // 改变Vuex.state.tokenStatus的值 this.updateTokenStatus(true) } }
8. 配置axios的错误判断
// 初始化用户信息 initUserInfo () { const p1 = this.$api.user.getUserInfo() p1.then(result => { this.data = result this.isEdit = false this.firstLoading = false }).catch(reason => { this.firstLoading = false this.isEdit = false // 目前后端是通过code为-1,返回错误信息 if (parseInt(reason.code) === -1) { this.$alert(reason.message, '提示', { type: 'error' }) } }) },
9. 拦截响应, 处理401,返回自定义错误
import router from '../../router' import axios from 'axios' import localStorage from 'localStorage' import { MessageBox } from 'element-ui' import store from '../../store/store' // http response 拦截器 axios.interceptors.response.use( response => { return response }, error => { if (error.response) { if (error.response.status === 401) { switch (error.response.status) { case 401: const route = localStorage.getItem('vip_entrance') router.replace({ path: route, query: { redirect: router.currentRoute.fullPath } }) if (store.state.tokenStatus) { // 饿了么框架弹框 MessageBox.alert('登录超时!', '提示', { type: 'error' }) // 修改tokenStatus状态,防止多次点击 store.commit('updateTokenStatus', false) } const data = { code: 1 } return Promise.reject(data) } } } return Promise.reject(error.response.data) } )
补充知识:vue 配置vuex在严格模式下出现是问题
我就废话不多说了,大家还是直接看代码吧~
需要关闭严格模式,不然会报错
import Vue from "vue"; import Vuex from "vuex"; import createPersistedState from "vuex-persistedstate"; import * as Cookies from "js-cookie"; import user from "./modules/user"; import myCen from "./modules/myCen"; import registered from "./modules/registered"; Vue.use(Vuex); export default new Vuex.Store({ strict: false, //关闭严格模式 modules: { user, myCen, registered }, // 持久化储存 plugins: [ createPersistedState({ storage: { getItem: key => Cookies.get(key), setItem: (key, value) => Cookies.set(key, value, { expires: 7 }), removeItem: key => Cookies.remove(key) } }) ] });
以上这篇Vue 401配合Vuex防止多次弹框的案例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。