52. Axios of Vue

table of Contents

git : https://gitee.com/cxy-xupeng/vue-axios.git

1. What are the network request methods in Vue

Second, the basic use of axios

Three, concurrent requests

Four, axios global configuration

Five, axios instance

Six, package module

Seven, axios interceptor


git :https://gitee.com/cxy-xupeng/vue-axios.git

1. What are the network request methods in Vue

1.ajax

  • Configuration and invocation are very confusing
  • Coding is also uncomfortable

2.jquery-ajax

  • Jquery is not needed in Vue development. If you use this method, you need to specifically quote jquery

3.View-resource

  • Vue does not update this anymore, there are hidden dangers

4.axios

  • Recommend this

 

Second, the basic use of axios

1. Create a project

2. Install axios

npm install axios --save

3. Basic use of axios

axios({
  url:'http://123.207.32.32:8000/home/multidata',
  method:'get'
}).then(res=>{
  console.log(res)
})

axios({
  url:'http://123.207.32.32:8000/home/data',
  params:{
    type:'pop',
    page:1
  },
  method:'get'
}).then(res=>{
  console.log(res)
})

 

Three, concurrent requests

 

axios.all([
  axios({
    url:'http://123.207.32.32:8000/home/multidata',
  }),
  axios({
    url:'http://123.207.32.32:8000/home/data',
    params:{
      type:'pop',
      page:1
    },
  })])
.then(axios.spread((res1,res2)=>{
      console.log(res1)
      console.log(res2)
}))

 

Four, axios global configuration

Do global configuration for some fixed ones.

axios.defaults.baseURL = 'http://123.207.32.32:8000'
axios.defaults.timeout = 5000

 

Five, axios instance

const instance1 = axios.create({
  baseURL:'http://123.207.32.32:8000',
  timeout:10000
})
instance1({
  url:'/home/multidata',
}).then(res=>{
  console.log(res)
})
instance1({
  url:'/home/data',
  params:{
    type:'pop',
    page:1
  },
}).then(res=>{
  console.log(res)
})

 

Six, package module

main.js

//封装request模块
import {request} from './network/request.js'
request({
  url:'/home/multidata'
}).then(res=>{console.log(res)}).catch(err=>{console.log(err)})

request.js

import axios from 'axios'

export function request(config){
  //1.创建axios实例
  const instance = axios.create({
    baseURL:'http://123.207.32.32:8000',
    timeout:5000
  })

  //2.发送真正的请求
  return instance(config)
}

 

Seven, axios interceptor

  instance.interceptors.request.use(res=>{
    console.log(res)
    //(1)config中的一些信息不符合服务器要求
    //(2)每次发送网络请求时,显示一个请求的图标
    //(3)某些请求必须携带特殊信息(token)
    return res
  },err=>{
    console.log(err)
  })

  instance.interceptors.response.use(res=>{
    console.log(res)
    return res.data
  },err=>{
    console.log(err)
  })

 

Guess you like

Origin blog.csdn.net/qq_40594696/article/details/111195533