美文网首页
vuex+axios封装

vuex+axios封装

作者: 萘小蒽 | 来源:发表于2021-07-20 09:43 被阅读0次

以一个简单登录为例
1. 先配置aixos,这里用到了element-ui的提示组件。
工具模块@/uitl/aixos.js

/**
 *
 * http配置
 * 
 */
// 引入axios以及element ui中的loading和message组件
import Axios from 'axios'
import store from '../store'
import router from '../router/router';
//请求对token的操作
import { getToken, setToken, removeToken } from '@/util/auth'; 
import { Loading, Message } from 'element-ui'

let axios = Axios.create({
  timeout: 10000,
  headers: {
    'Content-Type': "application/json;charset=utf-8"
  }
});

// 超时时间
if (store.online) axios.defaults.timeout = 13000;
else axios.defaults.timeout = 0;
//跨域请求,允许保存cookie
axios.defaults.withCredentials = true;
//跨域请求,本地接口测试。
let ip = 'http://192.168.215.38:9999';
// Nginx 做转发
axios.defaults.baseURL = ip;
let loadinginstace
let cfg, msg;
msg = '服务器君开小差了,请稍后再试';
//HTTPrequest拦截
axios.interceptors.request.use(config => {
  loadinginstace = Loading.service({
    fullscreen: true
  });
  if (store.getters.token) {
    config.headers['Authorization'] = 'Bearer ' + getToken()// 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
  }
  return config
}, error => {
  return Promise.reject(error)
})
//HTTPresponse拦截,根据自己返回的res,需求自作修改.
axios.interceptors.response.use(
  response => {
    loadinginstace.close();
    const res = response.data
    if (res.code === 1) {
      message(res.msg, 'error')
      return Promise.reject(res)
    }
    return response
  },
  error => {
    loadinginstace.close();
    const res = error.response
    if (res.status === 478 || res.status === 403) {
      message(res.data.msg, 'error')
    } else if (res.status === 400) {
      message(res.data.error_description, 'error')
    } else if (res.status === 202) { //三方未绑定
      this.$router.push({ path: '/' })
    } else if (res.status === 503) {//服务异常
      message(res.data, 'error')
    } else if ((res.status === 401 && res.statusText == 'Unauthorized') || res.data.error == 'invalid_token' || res.data.error == 'unauthorized') {//token失效
      store.dispatch('FedLogOut').then(() => {
        router.push('/login')
      })
    } else {
      message(res.data.message, 'error')
    }
    return Promise.reject(error)
  }
)
export function message (text, type) {
  Message({
    message: text,
    type: type,
    duration: 5 * 1000,
    center: true
  })
}
export default axios

2. 请求API封装
已登录接口模块为例 @/api/user.js

//user.js
import request from '@/util/axios'
//接口以及参数已自己项目需求自作修改
export const loginByUsername = (username, password, code, randomStr) => {
  var grant_type = 'password'
  var scope = 'server'
  return request({
    url: '/auth/oauth/token',
    headers: {
      'Authorization': 'Basic bGltaW46bGltaW4='
    },
    method: 'post',
    params: { username, password, randomStr, code, grant_type, scope, mark: 2 }
  })
}

3. store目录配置

下面是我的vuex模块的文件目录,根据项目结构自行修改。

store
先看管理登录的配置store/modulses/user.js

import { getToken, setToken, removeToken } from '@/util/auth'
import { loginByUsername } from '@/api/user'
const user = {
  state: {

  },
  actions: {
    //根据用户名登录
    LoginByUsername ({ commit, state, dispatch }, userInfo) {
      return new Promise((resolve, reject) => {
        loginByUsername(userInfo.username, userInfo.password, userInfo.code, userInfo.redomStr).then(res => {
          const data = res.data;
          setToken(data.access_token)
          resolve(res.data);
        }).catch(() => { })
      })
    }
  }
  

}
export default user

@/store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'

Vue.use(Vuex)
const store = new Vuex.Store({
  modules: {
    user
  },
  getters,
})

export default store

main.js引入store

import store from './store';
//省略很多代码
export function createApp() {
  const app = new Vue({
    router,
    store,
    render: h => h(App)
  })
  return { app, router, store }
}

相关文章

  • vuex+axios封装

    以一个简单登录为例1. 先配置aixos,这里用到了element-ui的提示组件。工具模块@/uitl/aixo...

  • vuex+axios了解一下

    转自:https://www.cnblogs.com/wisewrong/p/6402183.htmlVue 原本...

  • vuex+axios 的开发流程记录

    相关文档 vuex: https://vuex.vuejs.org/zh/ 是否有必要使用vuex vuex是vu...

  • JavaScript面向对象与设计模式

    1. 面向对象 1.1 封装 封装的目的在于将信息隐藏。广义的封装不仅包括封装数据和封装实现,还包括封装类型和封装...

  • 02.OOP面向对象-3.一些理解

    对封装的理解?封装,类本身就是一个封装,封装了属性和方法。方法也是封装,对一些业务逻辑的封装。私有也是封装,将一些...

  • 封装微信小程序请求

    封装wx.request 封装api 封装请求调用

  • python 文件及文件夹的操作和异常捕获

    1、面向对象的特征:封装、继承、多态 1.1、封装: 函数一种封装,封装了一些逻辑代码 类也是一种封装,封装属性和...

  • node学习4

    Nodejs 路由模块封装、封装仿照 express 的路由 Nodejs 路由模块封装 封装仿照 express...

  • 我的vuex+axios请求数据的分层

    图示流程 先上我的流程图 目录结构 我是这样做的 axios相关配置 定义全局配置,当然是网上抠的,再稍改一些 s...

  • 封装组件

    封装tab组件封装曝光加载组件封装轮播组件 代码

网友评论

      本文标题:vuex+axios封装

      本文链接:https://www.haomeiwen.com/subject/vsmvwctx.html