首页 > 解决方案 > 如何在 vue 中使用全局变量,它不会更新计算变量?

问题描述

我正在构建一个 webapp,现在正在使用 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 完成时它似乎没有更新。这里出了什么问题。计算值不会更新全局变量吗?

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

标签: javascriptfirebasevue.jsfirebase-authenticationvuetify.js

解决方案


使用watch而不是计算属性。

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

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

PS:假设,你可以访问$userData整个 Vue 应用程序。


推荐阅读