第一步 npm下载响应的包
$ npm install axios --save
第二步
在main.js里写
import axios from 'axios'; Vue.prototype.$axios = axios;
下面的代码为在页面开始时候加载对应的方法:这里可以看到 加载的就是qwe()方法
mounted:function:这个方法,是和methods同级的!
mounted:function(){
this.qwe()
}, 接下来,我直接列举出一个简单的无参数GET方法 注意:这个方法是放在methods里面的
qwe(){
this.$axios.get('http://81.71.147.62:8000/api/baeUser/showAllUser',{
}).then(function(res){
console.log(res);
}).catch(function (error) {
console.log(error);
});
}, 看到这里,应该明白了Vue之axios基础使用 接下来将放出Vue之axios的 GET POST 带参数方法
// created:vue生命周期中的钩子函数,在这个时间点,data中的数据已经注入到响应式系统中
created(){
axios.get('api/getData.php',{ // 还可以直接把参数拼接在url后边
params:{
title:'眼镜'
}
}).then(function(res){
this.goodsList = res.data;
}).catch(function (error) {
console.log(error);
});
} axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.log(error);
});
// 注意: 如果发送请求时,发现传递的参数是对象,那么可用如下方式传参数
// var params = new URLSearchParams();
// params.append('title', '眼镜');
// params.append('id',1);
// axios.post('/user', params)
// .then(function(res){})
// .catch(function(error){}); //获得用户信息的请求
function getUserAccount() {
return axios.get('/user/12345');
}
//获取用户许可证的请求
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all( [ getUserAccount(), getUserPermissions() ] )
.then(axios.spread(function (acct, perms) {
//两个请求现已完成
})
); 请求拦截器和响应拦截器
//请求拦截器
axios.interceptors.request.use(
function (config) {
// 在发送请求之前做些什么
return config;
},
function (error) {
// 对请求错误做些什么
return Promise.reject(error);
}
);
//响应拦截器
axios.interceptors.response.use(
function (config) {
// 对响应数据做点什么
return config;
},
function (error) {
// 对响应错误做点什么
return Promise.reject(error);
}
); Vue中axios在发送POST请求时,参数的处理
1. 下载安装第三方模块 qs -> npm install qs --save-dev
2. 处理方式
// 第一种: 直接在发送的时候,对数据进行qs.stringify处理
// 缺点: 如果项目大,有大量的请求需要发送,那么一个一个加会很麻烦
axios.post("/checkLogin.php", qs.stringify({
name, pwd
}));
// 第二种: 使用axios.create创建一个新的axios实例,统一对数据进行处理, 同时也要借助qs模块
const Axios = axios.create({
baseURL: '/api',
transformRequest: [function (data) {
const d = qs.stringify(data)
return d;
}]
})
Axios.post("/checkLogin.php", {
name, pwd
});
本文作者为DBC,转载请注明。