一、选择什么网络模块?
发送网络请求的方式有很多,下面来简单介绍一下:
1、传统的Ajax是基于XMLHttpRequest(XHR)
2、jQuery - Ajax
为什么不适用jQuery的Ajax?
在vue开发中不需要使用jQuery,因为jQuery很重量级。
3、vue官方在Vue1.x的时候,推出了Vue-resource。
Vue-resource角jQuery轻便很多,但在vue2.x之后,尤雨溪对Vue-resource不维护了,简言之,就是弃用了。
4、尤雨溪推荐使用axios。
二、axios功能特点
在浏览器中发送XMLHttpRequest请求
在node.js中发送http请求
支持Promise API
支持拦截请求和响应
转换请求和响应数据
三、axios支持多种请求方式
axios(config)
axios.request(config)
axios.get(url,[,config])
axios.delete(url,[,config])
axios.head(url,[,config])
axios.post(url,[,data[, config]])
axios.put(url,[,data[, config]])
axios.patch(url,[,data[, config]])
四、发送并发请求
有的时候,会同时发送多个请求。
使用axios.all,可以放入多个请求的数组。
axios.all([])返回的是一个数组,使用axios.spread可以将数组[res1,res2]展开为res1和res2。
import axios from 'axios'
export default {
name: 'app',
created(){
axios.all([axios.get('http://127.0.0.1:8080/getUserList'),
axios.get('http://127.0.0.1:8080/getUserPage',{
params: {pageNum: 1, pageSize: 10}
})
])。then(axios.spread((res1,res2) => {
console.log(res1)
console.log(res2)
}))
}
}
五、全局配置
import axios from 'axios'
export default {
name: 'app',
created(){
// 提取全局配置
axios.defaults.baseURL = 'http://127.0.0.1:8080'
axios.all([axios.get('/getUserList'),
axios.get('/getUserPage',{
params: {pageNum: 1, pageSize: 10}
})
])。then(axios.spread((res1,res2) => {
console.log(res1)
console.log(res2)
}))
}
}
六、创建axios实例
const instance1 = axios.create({
baseURL: 'http://127.0.0.1:8080',
timeout: 5000
})
instance1({
url: '/home/getUserList'
})。then(res => {
console.log(res);
})
instance1({
url: '/home/getUserPage',
params: {
type: 'pop',
page: 1
}
})。then(res => {
console.log(res);
})
const instance2 = axios.create({
baseURL: 'http://127.0.0.1:8081',
timeout: 10000,
// headers: {}
})
如需转载,请注明文章出处和来源网址:http://www.divcss5.com/html/h64973.shtml