正确解决vue中axios is not defined

本文介绍在Vue项目中如何正确配置并使用Axios进行前后端数据交互,包括引入Axios的方式及常见错误提示的解决方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

axios已经是安装好的状态
在学习vue时,前段请求后端数据时浏览器出现下面提示的错误
1.在main.js下

import VueAxios from 'vue-axios';
import axios from 'axios';

2.使用的npm 例子的代码如下

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

3.请求时浏览器出现以下错误

webpack-internal:///./node_modules/vue/dist/vue.esm.js:629 [Vue warn]: Error in created hook: "ReferenceError: axios is not defined"
found in
---> <Book> at src/components/Book.vue
   <App> at src/App.vue
     <Root>
     warn @ webpack-internal:///./node_modules/vue/dist/vue.esm.js:629

解决办法
在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;
      })
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值