I am creating a simple app mockup in VueJS, using Google Cloud Firestore as a backend.
I have a template up and running, and have the app successfully talking to the Firestore.
Below is the working component of one of my Vue components, which grabs some data from Firestore and logs to console:
<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>
So far so good. Console logs an array of metrics as required:
(3) ["Return On Equity", "Net Margin", "EPS"]
My next step is to transfer the data in ‘mydata’ and append it to the ‘options’ object, and this is where I’m running into trouble.
I’ve tried following the pattern of this tutorial https://www.youtube.com/watch?v=rUz4oz7dTno&t=491s and have inserted the following line of code underneath ‘console.log(mydata)’
this.options.push(mydata)
However I get the following error:
Uncaught (in promise) TypeError: Cannot read property 'options' of undefined at eval (MainScr.vue?d2a3:33)
I don’t understand why it can’t read the ‘options’ property? Any help would be much appreciated.
Advertisement
Answer
I believe it’s because of the scope. “this” goes out of scope of the function , hence it is not finding the property.
Try this way.
Inside your create(), as a first line , make a copy of “this” like below.
Var self = this;
And then, instead of this.options, do self.options