我目前正在尝试使用VueJS 3和Axios来访问一个简单的API并显示其结果数据。不幸的是,似乎除了示例ping示例之外的任何东西都让我感到困惑。
我遇到的问题是:data()方法似乎在 both created()和mounted()之后被调用,因此它应该示例化的值(在我的示例代码中,当getRandomVideos()和testMethod()执行时,random_vids和count不可用。
这使得在create()调用的方法中更改它们是不可能的,因为引用还不存在。
我使用的是Options API和created()钩子。请参阅下面的代码,注解了我执行它时得到的日志和警告:
<template>
<p class="title">some title idk</p>
<div>
{{random_vids}}
</div>
</template>
<script>
import axios from 'axios';
export default {
name: "home_fitness",
methods: {
data() {
return {
random_vids: [],
count: 1
}
},
async getRandomVideos(){
const path= "http://localhost:5001/random_videos"
try {
const res = await axios.get(path);
this.random_vids = res.data; // Warn: Property "random_vids" was accessed during render but is not defined on instance.
} catch (error) {
this.errorMessage = error;
console.error(error);
}
},
// this test method included in the hopes it makes my error easier to reproduce (also, i needed to make sure this wasn't async or axios shenanigans)
testMethod() {
console.log(this.count); // log: undefined
this.count = 2;
console.log(this.count); // log: 2
},
},
created() {
this.getRandomVideos();
this.testMethod();
}
};
</script>
字符串
当我更新源文件并保存它时,vue会将我的更改更新到正在运行的应用程序中; testMethod()不会再次运行(没有日志),所以我假设getRandomVideos也不会,但是我的示例中的第4行突然被来自API的预期数据填充。
之前对日志的修改确认了getRandomVideos()成功地从localhost:5001/random_vids中获取了API数据,API服务器日志确认了请求没有被重新运行。我写的代码成功地获取并存储了数据,由于文件更新导致它被写在DOM中,我想它一定知道它应该去哪里,但我真的不明白为什么它没有马上这样做。
我仔细阅读了指南和多个答案,甚至找到了simlar questions on StackOverflow,但没有解决我的问题。我想我犯了一个非常简单的错误,但我找不到哪一个。我可能错过了一些关于Vue的基本知识,但我无法弄清楚 * 是什么 *。
那么,为什么data()似乎是在 * create()之后执行的?为什么数据是可用的,但直到源代码更改后Vue热更新文件才出现?为什么尽管在data()中定义了 count,但 count 不可用?如何让random_vids在页面加载时正确显示在示例的第4行?
1条答案
按热度按时间camsedfj1#
data
不是一个方法,它是Options API的“选项”之一,其中methods
是另一个单独的选项。更改此:
字符串
对此:
型