Vue中axios的使用

浮夸小生。
2020-12-19 / 0 评论 / 372 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2020年12月19日,已超过1223天没有更新,若内容或图片失效,请留言反馈。

安装axios

[typing]npm i axios -S[/typing]


main.js中配置使用axios

<div>// 导入axios包
import axios from "axios"

// 设置请求的基准URL
axios.defaults.baseURL = "";

// 对返回的数据进行一层剖析处理
axios.interceptors.response.use(_ => {
    return _.data
})

// 给请求带上请求头(一般用于是否登录)
axios.interceptors.request.use(config => {
    config.headers["ticket"] = sessionStorage.getItem('ticket') || ""
    return config
})

// 设置请求头请求类型
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.headers.get['Content-Type'] = 'application/x-www-form-urlencoded';
axios.defaults.transformRequest = [function (data) {
    let ret = ''
    for (let it in data) {
      ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
    }
    return ret
}]

// 挂载到Vue原型上
Vue.prototype.axios = axios;</div>

组件内使用请求

<div><script>
    export default {
         created() {
              // GET请求
              this.getList(),

              // POST请求
              this.deleteList()
        },
        methods: {
              // GET请求
              async getList() {
                  const res = await this.axios.get("",{
                      params: { id: 123 }
                  })
                  console.log(res)
              },

              // POST请求
              async deleteList() {
                  const res = await this.axios.post("",{
                      id: 123
                  })
                  console.log(res)
              },
        }
    }
</script></div>
0

评论 (0)

取消