javascript - 如何在 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 中重新编译构建时,会出现用户名。当我然后刷新页面时,它不再起作用。
解决方案
使用watch
而不是计算属性。
watch:{
'$userData' = function(newValue){
...
this.name = newValue.name;
...
}
}
获取更多信息:https ://flaviocopes.com/vue-watchers/
PS:假设,你可以访问$userData
整个 Vue 应用程序。
推荐阅读
- flutter - 无法在颤动中调整svg图片的大小
- c++ - QQuickWidget 自定义大小调整模式
- docker - Traefik 似乎忽略了路由器的规则(错误?)
- docker - Teams OnPrem 上的 Bot Framework LUIS
- selenium - 尝试在本地而不是在 GitLab 中触发弹出窗口,给出 org.openqa.selenium.NoSuchWindowException: Browsing context has been discarded
- python - 尝试比较具有不同扩展名的两个声音文件
- python - 在 python 中设置 pandas 数据框的样式会使浮点值在小数点后有更多的零
- api - Selenium Scraping API 数据
- flutter - 我可以删除领导和行动之间的空间吗?
- html - 如何在 Visual Studio Code 中启动多个 HTML 文件?