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)