【问题标题】:How to use a global variable in vue, it does not update computed variables?如何在 vue 中使用全局变量,它不会更新计算变量?
【发布时间】:2020-05-20 17:40:38
【问题描述】:

我正在构建一个 web 应用程序,现在正在使用 firebase 实现身份验证。 我的登录界面正常工作,现在我想将此数据分享给应用程序的其余部分。

由于我没有使用 Vuex,我尝试使用 Vue.prototype.$userData= {} 来创建一个全局变量,因此我不必担心将其传递下去。

我在 app.js 中这样创建变量:

  mounted() {
    firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        //RETRIEVING SOME EXTRA USER DATA HERE
        firebase
          .firestore()
          .collection('users')
          .doc(user.uid)
          .get()
          .then(function(doc) {
            if (doc.exists) {
              console.log(doc.data()) //THIS LOG WORKS
              Vue.prototype.$userData = {...user, ...doc.data()};
            } else {
              // doc.data() will be undefined in this case
              console.log('No such document!');
            }
          })
          .catch(function(error) {
            console.log('Error getting document:', error);
          });
      }
    });
  }

然后我尝试在这样的组件中使用它:

  computed: {
    username: function () {
      if(this.$userData) {
        return this.$userData.naam;
      } else return "-";
    }
  }

但是当 $userData 完成时它似乎没有更新。这里出了什么问题。 计算值不会在全局变量上更新吗?

附:当我对代码进行更改以便在 npm run serve 中重新编译构建时,会出现用户名。当我刷新页面时,它不再起作用了。

【问题讨论】:

    标签: javascript firebase vue.js firebase-authentication vuetify.js


    【解决方案1】:

    使用watch 代替计算属性。

    watch:{
      '$userData' = function(newValue){
         ...
         this.name = newValue.name;
         ...
      }
    }
    

    获取更多信息:https://flaviocopes.com/vue-watchers/

    PS:假设,您可以在整个 Vue 应用程序中访问 $userData

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-09-22
      • 1970-01-01
      • 2014-07-20
      • 2013-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多