1.原因
axios实例没有all这个方法,all是axios的静态方法,静态方法和私有方法是不会被继承的
2.解决
在axios实例那里手动挂载这这个个方法
// 手动挂载2个方法
http.all = axios.all
http.spread = axios.spread
3.介绍
这里主要是对axios进行拦截请求和响应,所以我对他进行了二次封装,在项目中我用到了并发请求,发现all和spread报错is not a function。
// 二次封装axios
import axios from 'axios'
import {
Message,
} from 'element-ui';
// 设置基础公共的BASEURL
const BASEURL = '/api';
// 创建网络请求对象
const http = axios.create({
baseURL: BASEURL,
timeout: 5000
})
// 手动挂载2个方法
http.all = axios.all
http.spread = axios.spread
// 请求拦截器
http.interceptors.request.use(config => {
// console.log('config',config)
return config
}, error => {
return Promise.reject(error)
})
// 响应拦截器
http.interceptors.response.use(response => {
// console.log('response',response)
return response
}, error => {
Message({
showClose: true,
message: '请求数据出错啦',
type: 'error'
});
return Promise.reject(error)
})
export default http
在main.js中挂载到vue原型上
import http from './network/http'
Vue.prototype.$axios = http
4.并发请求
主要就是将我们的并发请求放入this. a x i o s . a l l ( ) 这 个 o p t i o n 数 组 里 面 , 然 后 通 过 t h i s . axios.all()这个option数组里面,然后通过this. axios.all()这个option数组里面,然后通过this.axios.spread获取相应的结果。
methods: {
selectAllGoods() {
return this.$axios.post(
"/shop/selectAllGoods",
this.$qs.stringify({ page: this.nowPage, size: this.selectCount }),
{
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
}
);
},
selectGoodsType() {
return this.$axios.post("/shop/selectGoodsType");
},
}
mounted() {
let that = this;
this.$axios.all([this.selectAllGoods(), this.selectGoodsType()]).then(
that.$axios.spread(function (res1, res2) {
console.log(res1)
console.log(res2);
//表格数据
that.tableData = res1.data.data;
// 总共有多少条
that.totalCount = res1.data.count;
//一级分类
that.level_one = res2.data.data;
// 存入本地存储
sessionStorage.setItem("tableData", JSON.stringify(that.tableData));
sessionStorage.setItem("level_one", JSON.stringify(that.level_one));
})
);
},