this.$axios.all() is not a function和this.$axios.spread()is not a function报错解决办法以及并发请求用法介绍

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()optionthis.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));
      })
    );
  },
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值