首页 > 解决方案 > 为什么反应值有时不会在模板中更新?(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>

我不明白为什么它有时会显示标题,有时却不显示。是否有另一种方法可以在没有语法的情况下绑定titlh3-tag的内容?{{}}

先感谢您!

编辑:

我已将{{}}语法更改为v-text这样: <h3 @click="displayCoursePreview" class="mt-5" v-text="titl"></h3> 现在它每次都可以工作,即使在重新加载后也是如此。谁能解释其中的区别以及为什么会这样?

标签: javascriptvue.jsasynchronousnuxt.js

解决方案


要回答原始问题,您可能在此组件和商店之间存在竞争条件。手表只有在安装后发现 this.$store.state.rehydrad 发生变化时才会触发“getSections”,但商店可能在安装此组件之前已经完成了该操作,因此手表永远不会被触发。

不知道为什么切换到 v-text 会改变这一点,也许它允许组件安装得稍微快一点,所以它在商店完成补液之前就被安装了?


推荐阅读