vue axios数据请求及vue中使用axios的方法
(编辑:jimmy 日期: 2025/10/26 浏览:3 次 )
axios 简介
axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:
--------------------------------------------------------------------------------
"axios"
然后在methods里面写数据的请求
methods:{
getInfo(){
let url = "url"
axios.get(url).then((res)=>{
//console.log(res)
this.list1 = res
})
}
在生命周期调用一下,一般我们数据请求使用的生命周期是Mounted
mounted() {
this.getInfo()
}
这样我们就完成了axios的get方法请求
然后我们简答的说一说post请求,post请求与get请求其实变得不多
postInfo() {
let url = "..."
var params = new URLSearchParams();
params.append('key', index);
axios.post(url, params).then((res) => {
console.log(res)
})
}
这样我们就可以成功的使用post方法请求数据了
补充:下面看下vue中使用axios
1.安装axios
npm:
$ npm install axios -S
cdn:
<script src="/UploadFiles/2021-04-02/axios.min.js">
2.配置axios
在项目中新建api/index.js文件,用以配置axios
api/index.js
import axios from 'axios';
let http = axios.create({
baseURL: 'http://localhost:8080/',
withCredentials: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
},
transformRequest: [function (data) {
let newData = '';
for (let k in data) {
if (data.hasOwnProperty(k) === true) {
newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&';
}
}
return newData;
}]
});
function apiAxios(method, url, params, response) {
http({
method: method,
url: url,
data: method === 'POST' || method === 'PUT' "http://localhost:8080/">http://localhost:8080/,这样调用的时候只需写访问方法即可
3.使用axios
注:PUT请求默认会发送两次请求,第一次预检请求不含参数,所以后端不能对PUT请求地址做参数限制
首先在main.js中引入方法
import Api from './api/index.js';
Vue.prototype.$api = Api;
然后在需要的地方调用即可
this.$api.post('user/login.do(地址)', {
"参数名": "参数值"
}, response => {
if (response.status >= 200 && response.status < 300) {
console.log(response.data);\\请求成功,response为成功信息参数
} else {
console.log(response.message);\\请求失败,response为失败信息
}
});
下一篇:vue插件实现v-model功能