javascript - 为什么反应值有时不会在模板中更新?(Vue)
问题描述
我有一个简单的h3
标签,其中包含一个绑定到反应数据属性的标题。我正在从 Firestore 数据库中获取值并将其分配给 data 属性。当我不通过客户端导航重新加载和访问页面时,一切正常。但是,一旦我重新加载标题值就会正确更新(在控制台日志和 vue 开发工具中看到),但 h3-tag 仍然为空。
这是代码:
<template>
<h3 @click="displayCoursePreview" class="mt-5">{{ titl }}</h3>
</template>
<script>
props: {
student: {
type: Boolean
}
},
watch: {
rehydrated: {
// Always triggers once store data is rehydrated (seems to work without any problems)
immediate: true,
async handler(newVal, oldVal) {
if (newVal) {
await this.getSections();
return this.getTopics();
}
}
}
},
data() {
return {
titl: null
};
},
computed: {
rehydrated() {
return this.$store.state.rehydrated; // Equals true once store is rehydrated from local storage
}
},
methods: {
getSections() {
console.log('running') // Runs every time
let ref = this.$store.state.courses;
var cid = this.student
? ref.currentlyStudying.cid
: ref.currentlyPreviewing.cid;
// Get Course Title
this.$fireStore
.collection("courses")
.doc(cid)
.get()
.then(doc => {
console.log(doc.data().name) // Logs correct title every time
this.titl = doc.data().name;
this.thumbSrc = doc.data().imgsrc;
})
.catch(err => console.log(err));
}
</script>
我不明白为什么它有时会显示标题,有时却不显示。是否有另一种方法可以在没有语法的情况下绑定titl
到h3
-tag的内容?{{}}
先感谢您!
编辑:
我已将{{}}
语法更改为v-text
这样:
<h3 @click="displayCoursePreview" class="mt-5" v-text="titl"></h3>
现在它每次都可以工作,即使在重新加载后也是如此。谁能解释其中的区别以及为什么会这样?
解决方案
要回答原始问题,您可能在此组件和商店之间存在竞争条件。手表只有在安装后发现 this.$store.state.rehydrad 发生变化时才会触发“getSections”,但商店可能在安装此组件之前已经完成了该操作,因此手表永远不会被触发。
不知道为什么切换到 v-text 会改变这一点,也许它允许组件安装得稍微快一点,所以它在商店完成补液之前就被安装了?
推荐阅读
- javascript - 如何在 CSS 中引用 document.createElement
- reactjs - 在 MERN TypeError 中出现错误:无法读取未定义的属性“地图”
- android - 包“com.instagram.android”的开发者警告
- dotnetnuke-9 - Dnn 9 - 将管理语言设置为英语,将站点语言设置为荷兰语
- c++ - 使用 Tensorflow 的 C++ ABI 兼容性问题
- angular - 更改路由并将数据传递给另一个组件
- angular - 在构造函数中获取 Ionic 4 存储令牌值的解决方案是什么,例如在运行时将令牌设置为 http 标头?
- oauth - eBay OAuth 无法获取令牌
- mysql - MySql 服务器不是从命令提示符启动的
- google-cloud-platform - 所需的复合索引不存在,但在 index.yaml 中定义