【问题标题】:firestore onSnapshot updates values, but not DOM in VueJSfirestore onSnapshot 更新值,但不更新 VueJS 中的 DOM
【发布时间】:2019-09-30 23:36:58
【问题描述】:

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

这是我的 .Vue 文件中的 sn-ps。

        <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;
      }
    });
  }

【问题讨论】:

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


    【解决方案1】:

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

    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 实例。

    【讨论】:

    • 哈哈,做到了!你是个天才。非常感谢你。我没有意识到它是这样工作的。我还在学习很多东西!
    • 我会在 9 分钟内将其标记为已回答,直到那时我才会这样做。
    猜你喜欢
    • 2019-10-12
    • 1970-01-01
    • 2018-10-06
    • 1970-01-01
    • 2018-08-04
    • 2020-02-05
    • 2018-01-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多