当前位置:网站首页 > 更多 > 站长帮 > 正文

[WEB] Vue2封装axios,axios在Vue.cli中的使用

作者:CC下载站 日期:2021-06-11 00:00:00 浏览:74 分类:站长帮

添加http.js文件

在src目录下新增一个目录utils,并新增一个js文件http.js,用以实现axios的封装

编辑http.js,首先导入axios

   import axios from 'axios'

定义Http Request公共信息,用以添加授权等

   axios.interceptors.request.use(
    config => {
        let token = 'lanol'
        config.headers.token = token;
        if (config.method == 'get') {
            config.params.token = token
        }
        if (config.method == 'post') {
            config.data.token = token
        }
        return config;
    },
    error => {
        return Promise.reject(err);
    }
)

封装Get方法

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

封装POST方法

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

封装patch请求

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

封装PUT请求

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

实现跨域

const downloadUrl = url => {
    let iframe = document.createElement('iframe')
    iframe.style.display = 'none'
    iframe.src = url
    iframe.onload = function() {
        document.body.removeChild(iframe)
    }
    document.body.appendChild(iframe)
}

Main.js中引用

import axios from 'axios'
import {get,post} from '@/utils/http.js'
Vue.prototype.$ajax = axios
Vue.prototype.$post = post
Vue.prototype.$get = get

使用http.js

<template>
  <div id="app">
      {{Lan}}
  </div>
</template>

<script>
import axios from '@/utils/http.js'
export default {
  name: 'app',
  components: {
  },
  data() {
      return {
          Lan: ''
      }
  },
  mounted() {
      this.$get('https://v1.hitokoto.cn').then((response)=>{
          this.Lan = response.hitokoto
          console.log(response);
      })
  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>


参考链接https://www.cnblogs.com/zhangbs/p/9681032.html

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯