axios的安装和使用

2022-09-07 10:56:28

axios的安装和使用

安装

npm install axios

引入

在main.js中引入或者在封装的js里引入

import Axios from 'axios'
Vue.prototype.$axios=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);});

页面如果觉得直接这样写有点low,也可以自己封装httpRequest.js

封装

1.httpRequest,js:

import axiosfrom'axios';import qsfrom'qs'//这个只要安装了axios就可以直接引入var http= axios.create({
  baseURL:'/api',
  timeout:1000});

axios.defaults.headers.post['Content-Type']='application/x-www=-form-urlencoded'

http.param=(data={},contentType='application/x-www-form-urlencoded')=>{return contentType==='application/x-www-form-urlencoded'? qs.stringify(data):(contentType==='application/json'?JSON.stringify(data):data);}/**
 * get封装
 * @params:url
 * @params:params
*/exportfunctionhttpGet(url,param={}){returnnewPromise((resolve,reject)=>{
        http.get(url,{params:http.param(param)}).then(response=>{resolve(response.data)}).catch(err=>{reject(err)})})}/**
 * post封装
 * @params:url
 * @params:param
*/exportfunctionhttpPost(url,param={}){returnnewPromise((resolve,reject)=>{
        http.post(url,http.param(param)).then(response=>{resolve(response.data)}).catch(err=>{reject(err)})})}

2.main.js引入

// The Vue build version to load with the `import` command// (runtime-only or standalone) has been set in webpack.base.conf with an alias.import Vuefrom'vue'import Appfrom'./App'import axiosfrom'axios'import{httpGet,httpPost}from'@/assets/utils/httpRequest.js'

Vue.config.productionTip=false
Vue.prototype.$axios=axios
Vue.prototype.$httpGet=httpGet
Vue.prototype.$httpPost=httpPost/* eslint-disable no-new */newVue({
  el:'#app',
  components:{ App},
  template:'<App/>'})

3.页面组件中就可以用了

getList(){this.$httpGet('/ams-wangqin/userInfo/queryUserInfoListByParams',{userName:this.input}).then(res=>{
        console.log(res)this.tableData=res;}).catch(err=>{
        console.log(err)})}
  • 作者:口袋の的天空
  • 原文链接:https://blog.csdn.net/qq_39928481/article/details/108436666
    更新时间:2022-09-07 10:56:28