I understand that Firebase returns data asynchronously, so I actually placed the variable inside the once()
function. But I cannot access the variable
called whatever
. While writing this question I also figured I could try set the firebase data directly to the data()
.
My question is how can I pass the data in VueJS data() function so that when the user either refreshes or logs back in the data populates the input field in these two different options?
<template lang="html">
<div class="">
<label for="">Name</label>
<input id="nameId" type="text" v-model="name" />
</div>
</template>
export default {
name: 'app',
data () {
return {
name: '',
}
},
methods:{
var whatever = [];
var query = dbRef.orderByKey();
query.once('value')
.then(function (snapshot) {
snapshot.forEach(function(childSnapshot) {
var childData = childSnapshot.child('name').val();
this.whatever.push(childData);
// Option 1: use out of scope
this.name = whatever;
// Option 2: directly populate data
this.name = childData;
});
});
}
Try the following, which incorporates the changes from my comment. To clarify, using a computed property to execute the query would be ideal, as it will execute at a certain point in the lifecycle.
You can also use a method but you would have to call it at some point - you mention on page reload, then one of the component lifecycle hooks would be ideal.
The below is a computed property approach. The property is bound to a v-model so Vue might also force you to define a setter also but that's straightforward.
export default {
name: 'app',
data() {
return {
name: '',
}
},
computed: {
fullName() {
var query = dbRef.orderByKey();
query.once('value')
.then((snapshot) => {
snapshot.forEach((childSnapshot) => {
this.name = childSnapshot.child('name').val();
});
});
}
}
}
<template lang="html">
<div class="">
<label for="">Name</label>
<input id="nameId" type="text" v-model="fullName" />
</div>
</template>