我正在 VueJS 中创建一个简单的应用程序模型,使用 Google Cloud Firestore 作为后端。
我已经启动并运行了一个模板,并且应用程序成功与 Firestore 通信。
下面是我的一个 Vue 组件的工作组件,它从 Firestore 获取一些数据并将日志记录到控制台:
<script>
import db from './firebaseInit'
export default {
name: 'MainScr',
data () {
return {
msg: 'Welcome to Your Vue.js App',
options: [],
}
},
created () {
var docref = db.collection('UI_Elements').doc('Metric_Dropdown')
docref.get().then(function(doc) {
if (doc.exists) {
const mydata = doc.data().Metrics
console.log(mydata)
} else {
console.log("No such document")
}
})
}
}
</script>
到目前为止一切顺利。控制台根据需要记录一系列指标:
(3) ["Return On Equity", "Net Margin", "EPS"]
我的下一步是传输“mydata”中的数据并将其附加到“options”对象,这就是我遇到麻烦的地方。
我尝试遵循本教程的模式 https://www.youtube.com/watch?v=rUz4oz7dTno&t=491s并在“console.log(mydata)”下插入以下代码行
this.options.push(mydata)
但是我收到以下错误:
Uncaught (in promise) TypeError: Cannot read property 'options' of undefined
at eval (MainScr.vue?d2a3:33)
我不明白为什么它无法读取“选项”属性?任何帮助将不胜感激。
最佳答案
我相信这是因为范围的原因。 “this”超出了函数的范围,因此它没有找到该属性。
试试这个方法。
在 create() 中,作为第一行,复制“this”,如下所示。
var self = this;
然后,使用 self.options 代替 this.options
关于javascript - Vue JS 和 Firestore - 未捕获( promise 中)TypeError : Cannot read property of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50185542/