vueにおけるaxiosパッケージ

12423 ワード

1.axiosのダウンロード
cnpm install axios --save
2.staticディレクトリの下でhttpを作成する.js
import axios from 'axios';
import { Message } from 'element-ui';

axios.defaults.timeout = 5000; //      
axios.defaults.baseURL ='https://pro.junmeiauto.cn:8443/'; //      


//http request    
axios.interceptors.request.use(
  config => {
    // const token = getCookie('  ');           cookie  ,  js-cookie
    config.data = JSON.stringify(config.data);
    config.headers = {
      'Content-Type':'application/x-www-form-urlencoded'
    }
    // if(token){
    //   config.params = {'token':token}
    // }
    return config;
  },
  error => {
    return Promise.reject(err);
  }
);


//http response    
axios.interceptors.response.use(
  response => {
    if(response.data.errCode ==2){
      router.push({
        path:"/login",
        querry:{redirect:router.currentRoute.fullPath}//       
      })
    }
    return response;
  },
  error => {
    Message({
      Message:error.message,
      type:'error',
      duration:5*1000
    });
    return Promise.reject(error)
  }
)


/**
 *   get  
 * @param url
 * @param data
 * @returns {Promise}
 */

export function fetch(url,params={}){
  return new Promise((resolve,reject) => {
    axios.get(url,{
      params:params
    })
      .then(response => {
        resolve(response.data);
      })
      .catch(err => {
        reject(err)
      })
  })
}


/**
 *   post  
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.post(url,data)
      .then(response => {
        resolve(response.data);
      },err => {
        reject(err)
      })
  })
}

/**
 *   patch  
 * @param url
 * @param data
 * @returns {Promise}
 */

export function patch(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.patch(url,data)
      .then(response => {
        resolve(response.data);
      },err => {
        reject(err)
      })
  })
}

/**
 *   put  
 * @param url
 * @param data
 * @returns {Promise}
 */

export function put(url,data = {}){
  return new Promise((resolve,reject) => {
    axios.put(url,data)
      .then(response => {
        resolve(response.data);
      },err => {
        reject(err)
      })
  })
}

3.main.jsに導入
import axios from 'axios'
import {post,fetch,patch,put} from "../static/js/http";

Vue.prototype.$axios=axios;
Vue.prototype.$post=post;
Vue.prototype.$fetch=fetch;
Vue.prototype.$patch=patch;
Vue.prototype.$put=put;

4.コンポーネントでの直接使用
methods:{
  SubmitLogin:function () {
    var params = {
      nickname: this.ruleForm.nickname,
      administratorPassword: this.ruleForm.administratorPassword,
    };
    this.$fetch("backend/administrator/login",params)
      .then((response)=>{
        if(response.msg=='  '){
          this.$message({
            type:'success',
            message:'    '
          });
          this.$router.push('/readme');
        }
      })
  }
}