vue项目axios封装

vue项目axios封装

一、下载 axios

npm install axios -S

二、引用

一般会在项目的src目录中,新建一个request文件夹,然后在里面新建一个http.js和一个api.js文件。http.js文件用来封装我们的axios,api.js用来统一管理我们的接口

三、引用(http.js文件)

import axios from 'axios'; // 引入axios
import QS from 'qs'; // 引入qs模块,用来序列化post类型的数据,后面会提到
import router from '../router';
import store from './../store/index'; (四、说明此问题)

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.NODE_ENV === 'production' ? 'http://192.168.0.151:8089/api/v2' : 'http://192.168.0.151:8089/api/v2', // api base_url
  timeout: 60000 // 请求超时时间
})

// 请求超时时间
service.defaults.timeout = 10000;

// post请求头
service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

// 请求拦截器
service.interceptors.request.use(
  config => {
    // 每次发送请求之前判断是否存在token,如果存在,则统一在http请求的header都加上token,不用每次请求都手动添加了
    // 即使本地存在token,也有可能token是过期的,所以在响应拦截器中要对返回状态进行判断
    const token = store.state.token;
	token && (config.headers.Authorization = token);
	   return config;
	 },
	 error => {
	   return Promise.error(error);
	 })
	 // 响应拦截器
	service.interceptors.response.use(
	 response => {
	   if (response.status === 200) {
	     return Promise.resolve(response);
	   } else {
	     return Promise.reject(response);
	   }
	 },

      // 服务器状态码不是200的情况
		  error => {
		    if (error.response.status) {
		      switch (error.response.status) {
		        // 401: 未登录
		        // 未登录则跳转登录页面,并携带当前页面的路径
		        // 在登录成功后返回当前页面,这一步需要在登录页操作。
		        case 401:
		        router.replace({
		            path: '/login',
		            query: { redirect: router.currentRoute.fullPath }
		          });
		          break;
		        // 403 token过期
		        // 登录过期对用户进行提示
		        // 清除本地token和清空vuex中token对象
		        // 跳转登录页面
		        case 403:
		        // 消息弹窗,可自己封装,可引用(五、单独说明)
		          this.$my_message({
		            content: '登录过期,请重新登录',
		            time: 1000,
		            type: 'info', // info/success/warning/error,默认info
		            hasClose: true
		          });
		           // 清除token
		          localStorage.removeItem('token');
		          store.commit('loginSuccess', null);
		          // 跳转登录页面,并将要浏览的页面fullPath传过去,登录成功后跳转需要访问的页面
		          setTimeout(() => {
		            router.replace({
		             path: '/login',
		              query: {
		                redirect: router.currentRoute.fullPath
		              }
		            });
		          }, 1000);
		            break;
		        // 404请求不存在
		        case 404:
		          this.$my_message({
		            content: '网络请求不存在',
		            tie: 1500,
		            hasClose: true
		          });
		          break;
		           // 其他错误,直接抛出错误提示
		        default:
		          this.$my_message({
		            content: error.response.data.message,
		            time: 1500,
		            hasClose: true
		          });
		      }
		      return Promise.reject(error.response);
		    }
		  }
		);
		export {
		 service as axios
		}

四、vuex引入

npm install vuex --save

1、新建一个store文件夹(这个不是必须的),并在文件夹下新建index.js文件,文件中引入我们的vue和vuex。在一个模块化的打包系统中,您必通过 Vue.use() 进行引用:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

export default new Vuex.Store({
})
代码片

这步操作结束,vuex就算引用成功了。

2.可以在main.js文件中在实例化 Vue对象时加入 store 对象,这可以把store的实例注入所有的子组件中,如下图所示:

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'

new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

五、消息提示窗

1、在components里创建组件message文件,包含index.js和Message.vue文件
如图Message.vue

<template>
  <transition name="fade">
    <div class="message" :class="type" v-if="visible">
      <i class="icon-type iconfont" :class="'icon-'+type"></i>
		<div class="content">{{content}}
		<i v-if="hasClose" class="btn-close iconfont icon-close"     @click="visible=false"></i>
		</div>
	 </div>
	</transition>
 </template>
 <script>
  export default {
    name: "MyMessage",
    data() {
      return {
        content: '',
        time: 3000,
        visible: false,
        type:'info',//'success','warning','error'
        hasClose:false,
      }
    },
	 mounted() {
	      this.close()
	    },
	    methods: {
	      close() {
	        window.setTimeout(() =>{
	          this.visible = false
	        }, this.time);
	      }
	    }
	  }
	</script>
	<style scoped>
  .fade-enter-active,
  .fade-leave-active {
    transition: opacity .3s;
  }

  .fade-enter,
  .fade-leave-to {
    opacity: 0
  }
  .message {
    position: fixed;
    top: 40px;
    text-align: center;
    left: 50%;
    transform: translateX(-50%);
    min-width: 400px;
    padding: 10px 20px;
     font-size: 14px;
    line-height: 1.4;
    border-radius: 4px;
    z-index: 1000;
    box-shadow: 0 0 10px rgba(0, 0, 0, .3);
    color: red;
    /*  // &.info
        // &.success
        // &.error
        // &.warning */
  }

如图index.js

import Vue from 'vue'
import Message from './Message.vue'

const messageBox = Vue.extend(Message)
Message.install = function (options, type) {
  if (options === undefined || options === null) {
    options = {
      content: ''
    }
  } else if (typeof options === 'string' || typeof options === 'number') {
	  options = {
	      content: options
	    }
	    if (type != undefined && options != null) {
	      options.type = type;
	    }
	  }
	  let instance = new messageBox({
    data: options
  }).$mount()

  document.body.appendChild(instance.$el)
   Vue.nextTick(() => {
    instance.visible = true
  })
}

export default Message

2、main.js全局引入组件

import Message from '@/components/message'
Vue.prototype.$my_message = Message.install;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值