javascript - firestore onSnapshot 更新值,但不更新 VueJS 中的 DOM

标签 javascript firebase vue.js dom google-cloud-firestore

我正在使用 onSnapshot 监听 Vue 中的实时更新。我可以看到数据正在从 onSnapshot 加载,但它没有在 DOM 中更新。这可能只是一个非常愚蠢的错误,我只编程了大约一个多月,我只是不明白一些东西,我的谷歌搜索技能让我失望。浏览器显示“No State Listed”,而不是 DB 和 console.log 中的实际值。

这是我的 .Vue 文件中的片段。

        <div>
          <span class="grey--text">State:</span>
          <span class="grey--text">{{ state }}</span>
        </div>



export default {
  components: { VoterRegistration },
  data() {
    return {
      state: "No State Listed"
    };
  },
  methods: {},
  created() {
    auth.onAuthStateChanged(user => {
      if (user) {
        db.collection("users")
          .doc(user.uid)
          .onSnapshot({ includeMetadataChanges: true }, function(doc) {
            console.log(doc.data()); // shows all the data I want
            this.state = doc.data().state;
            console.log(this.state); //this shows correct value in firestore db
          });

        this.loggedIn = true;
      } else {
        this.person = "User not logged in";
        this.loggedIn = false;
      }
    });
  }

最佳答案

你可以试试换成箭头功能吗?

db.collection("users")
          .doc(user.uid)
          .onSnapshot({ includeMetadataChanges: true }, (doc) => {
            console.log(doc.data()); // shows all the data I want
            this.state = doc.data().state;
            console.log(this.state); //this shows correct value in firestore db
          });

我认为 function(doc) 中的 this 不是 Vue 实例。

关于javascript - firestore onSnapshot 更新值,但不更新 VueJS 中的 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56122002/

相关文章:

laravel - Axios 响应拦截器 : unable to handle an expired refresh_token (401)

typescript - 为用 Typescript 编写的 Vue 组件生成 d.ts 文件

javascript - Featherlight - 如何使用 javascript 打开灯箱?

javascript - 将一个 ArrayBuffer 读/写/复制到另一个具有偏移量的 ArrayBuffer

javascript - 反对在 JavaScript 代码块中包含服务器端脚本的论点是什么?

ios - 如何从 Rest API 发送推送通知

javascript - Chartjs 条形图图例

javascript - Visual Studio 2015 JavaScript 语言服务陷入下载不存在的引用文件的无限循环

javascript - 使用 jQuery/JavaScript 在 Firebase 中嵌套数组

javascript - 使用作为参数传递给 url 的 jsonld 数据加载 vue 应用程序