vue中使用axios

安装

npm install axios

执行GET请求

// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// 可选地,上面的请求可以这样做
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

执行POST请求

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

全局的axios默认值

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

更多详细内容请看官网npm-axios

具体使用方法一:全局引入

在 main.js 文件中全局引入

// main.js
import Vue from 'vue'
import axios from 'axios'

axios.defaults.baseUrl = "http://123.456.789:1000/api" // 假设的url

// 会将对象编码为键值对
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

// 会将对象变为 json字符串,两者选其一
axios.defaults.headers.post['Content-Type'] = 'application/json'

Vue.prototype.$axios = axios

然后在组件中使用axios

// Mycomponent.vue
<template>
...
</template>

<script>
export default {
    mounted(){
        this.$axios.get('/user?ID=123').then(res => console.log(res)).catch(( )=>{ });
    }
}
</script>

当然也可以使用 async/await 语法,请自行搜索。

方法二:抽离公共部分

此方法好处:可以单独管理 axios 所有配置,还可以加入各种拦截器,各种配置,不用污染 main.js

创建 api 文件夹

在此文件夹下新建文件 fetch.js

// fetch.js
import axios from 'axios'

const axiosInstance = axios.create({
    baseUrl: "http://api.example.com/",
    timeout: 10000,
})

export default axiosInstance

然后将所有的 api 分成一个个文件夹

// user.js
import fetch from './fetch'

export default getUserInfo(uid){
    return fetch({
        url: 'userinfo',
        params: { uid: uid },
    })
}

然后在组件中使用 getUserInfo 方法即可

// user.vue
<template>
...
</template>

<script>
import { getUserInfo } from '@/api/user'
export default {
    mounted() {
        getUserInfo(123).then(...).catch(...)
    }
}
</script>

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值