3、全局使用
//main.js
import axios from ‘axios’
Vue.prototype.$axios = axios
4、基本使用案例
执行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);
});
执行多个并发请求
function getUserAccount () {
return axios.get(‘/user/12345’);
}
function getUserPermissions () {
return axios.get(‘/user/12345/permissions’);
}
axios.all([getUserAccount(), getUserPermission()])
.then(axios.spread(function (acct, perms) {
// 两个请求都执行完成
}));
以上为基本使用,现在通过实例中实践一下
假如现在有某个接口(API),我们需要通过get请求调用,然后将返回数据渲染在页面上
api:https://api.apiopen.top/getJoke
入参:page=1、count=2、type=video
根据上面的基本使用案例可知,可以使用两种方式,接下来一一验证
1、URL地址参数拼接
由上面的api和入参可得拼接后的URL为:https://api.apiopen.top/getJoke?page=1&count=2&type=video(api后?将参数拼接,多个参数用&连接)
我是A组件
刷新页面,打开F12,切换到Network,发现此时页面发送了请求
切换到Console,查看控制台打印信息
我们已经成功获取接口的响应信息(返回值) ,数据结构为json格式,此时我们可以将想要的数据渲染到页面上,展开查看json数据
如我们想要将红色部分的信息渲染在页面上,此时可以对响应信息稍作处理
我是A组件
{ {result}}
页面显示效果