Error in mounted hook: "TypeError: Cannot read property 'get' of undefined"
时间: 2023-09-29 12:03:49 浏览: 51
当在组件中使用axios时,如果直接使用Vue.use(axios)进行引用,会出现错误"Error in mounted hook: TypeError: Cannot read property 'XXX' of undefined"。因为axios不能像其他组件一样直接通过Vue.use()进行引用。
为了使axios能够被其他组件使用,你需要将axios改写为Vue的原型属性,并将其绑定到Vue.prototype上。你可以使用以下代码将axios绑定到Vue的原型上:
```javascript
Vue.prototype.axios = axios
```
然后,在你的组件中使用this.axios进行引用,例如:
```javascript
this.axios.get('/user')
.then(res => {
this.result = res.data;
});
```
另外,你也可以自定义变量的名字,将axios绑定到Vue的原型上,例如:
```javascript
Vue.prototype.$ajax = axios
```
然后,在使用axios时,可以使用this.$ajax进行调用:
```javascript
this.$ajax.get('/user')
.then(res => {
this.result = res.data;
});
```
如果你还没有安装axios,你需要通过npm install axios --save命令来安装axios,并在main.js中引用axios:
```javascript
import axios from 'axios'
```
总结来说,当出现"Error in mounted hook: TypeError: Cannot read property 'get' of undefined"错误时,是因为你没有正确引入和使用axios。你需要将axios改写为Vue的原型属性,并正确引用它。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [Vue中使用axios (Error in mounted hook: “TypeError: Cannot read property ‘XXX‘ of undefined“ ...](https://blog.csdn.net/qq_40738077/article/details/98326806)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]