网络编程 
首页 > 网络编程 > 浏览文章

vue axios数据请求及vue中使用axios的方法

(编辑:jimmy 日期: 2024/5/30 浏览: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弹窗组件的实现示例代码
下一篇:vue插件实现v-model功能
高通和谷歌日前宣布,推出首次面向搭载骁龙的Windows PC的优化版Chrome浏览器。
在对骁龙X Elite参考设计的初步测试中,全新的Chrome浏览器在Speedometer 2.1基准测试中实现了显著的性能提升。
预计在2024年年中之前,搭载骁龙X Elite计算平台的PC将面世。该浏览器的提前问世,有助于骁龙PC问世就获得满血表现。
谷歌高级副总裁Hiroshi Lockheimer表示,此次与高通的合作将有助于确保Chrome用户在当前ARM兼容的PC上获得最佳的浏览体验。