Vue 3 (CLI):无法读取未定义的属性(读取"get")



当切换到Vue 3 CLI并因此重构代码时,this.$http.get('/api/todo/')不再工作。我没有从数据库中返回todo列表,而是在控制台中收到一个Cannot read properties of undefined错误:

app.js:209 Uncaught TypeError: Cannot read properties of undefined (reading 'get')
at Proxy.getTodos (Todos.vue?4897:38:1)
at Proxy.mounted (Todos.vue?4897:28:1)
at eval (runtime-core.esm-bundler.js?d2dd:2722:1)
at callWithErrorHandling (runtime-core.esm-bundler.js?d2dd:155:1)
at callWithAsyncErrorHandling (runtime-core.esm-bundler.js?d2dd:164:1)
at hook.__weh.hook.__weh (runtime-core.esm-bundler.js?d2dd:2697:1)
at flushPostFlushCbs (runtime-core.esm-bundler.js?d2dd:341:1)
at render (runtime-core.esm-bundler.js?d2dd:6247:1)
at mount (runtime-core.esm-bundler.js?d2dd:4440:1)
at app.mount (runtime-dom.esm-bundler.js?2725:1574:1)

此外,我观察到Vue devtools中的应用程序和组件列表都是空的。

在搜索和试验了几个小时的解决方案后,我还没有找到一个有效的解决方案。

这是导致问题的当前代码:

Todos.vue中,模板被渲染是因为我使用了";你好";,但我再也看不到任何列表项目了:

<template>
<div id="TODOS">
Hi there
<ol>
<li v-for="todo in v_todos" :key="todo.id">
<span style="color:red;">{{ todo.name }}</span>
</li>
</ol>
</div>
</template>

<script>
export default {
// el: "#TODOS",
name: 'Todos',

data() {
return {
v_todos: [],
}
},

computed: {},
components: {},

mounted() {
this.getTodos();
},

methods: {
getTodos: function () {
this.$http.get('/api/todo/')
.then((response) => { 
this.v_todos = response.data; 
})
.catch((err) => { 
console.log(err); 
})
},
}
</script>

App.vue中:

<template>
<div id="App">
<Todos />
</div>

</template>

<script>
import Todos from './components/Todos.vue'

export default {
name: 'App',
components: {
Todos
}
}
</script>

在HTML页面todos.HTML中:

...
<div id="App"></div>
...

base.html中,位于正文末尾:

<script type="text/javascript" src="{% static 'src/vue/dist/js/chunk-vendors.js' %}"></script>
<script type="text/javascript" src="{% static 'src/vue/dist/js/app.js' %}"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-resource@1.3.5"></script>

我对Vue完全陌生,所以如果能以简单易懂的方式提出解决方案,我将不胜感激。

添加到您的main.js

import axios from 'axios';
const app = createApp(App);
app.config.globalProperties.$http = axios;

最新更新