Vue3报错ReferenceError: axios is not defined完美解决

vue3与vue2版本变化相当大,即便在项目的plugins目录下使用npm install axios命令导入了axios.js使用axios.get还是会报错:axios is not defined

<script>
export default {
  methods: {
    handleClick(row) {
      console.log(row);
    },
    page(currentPage) {
      alert(currentPage);
    }
  },
  created() {
    const _this = this
    axios.get('http://localhost:8181/book/findAll/1/6').then(function (resp){
      _this.tableData = resp.data.content
      _this.total = resp.data.totalElements
    })
  },
  data() {
    return {
      total: null,
      tableData: null
    }
  }
}
</script>

错误发生后网页会有两种情况:1.页面只剩下空白和一两个箭头2.页面出现报错如下:

PageOne.vue:58  Uncaught (in promise) ReferenceError: axios is not defined
    at Proxy.created (PageOne.vue:58:1)

通过f12控制台都能发现问题都是 axios is not defined。

解决方案:既然说axios未被定义,在代码中的<script>标签下加一行导入包语句

import axios from 'axios';

就能完美解决问题。

方法一避坑:

至于网上的其他方法,例如下面的方法:

main.js加上如下代码:
Vue.prototype.$axios = axios
axios.get改为this.$axios.get调用,修改后不再报错

对于vue2而言有效,可是在Vue3项目中使用会出现以下新的错误:

Cannot read properties of undefined (reading 'prototype') at eval (main.js:6:1)

方法二避坑:

在main.js下 改成

import VueAxios from 'vue-axios';
import axios from 'axios';
Vue.prototype.$axios = axios;

例子的代码改成:

created(){
    const  _this = this
    this.$axios.get('http://localhost:8081/book/findall').then(function (resp) {
        _this.books = resp.data;
      })
  }

这样对Vue3项目会报新的错误PageOne.vue:58  Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'get') at Proxy.created.

以上不是很能解决问题的“解决办法”怎么解决实际问题还待各位网友考究,还是多去研究研究Vue3开发文档学习学习:Vue3 Ajax(axios)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值