当变量超出范围时使用 Firebase 填充 Vuejs 输入字段
Populate Vuejs input field with Firebase when Variables are out of scope
我知道 Firebase returns 数据是异步的,所以我实际上 将变量放在 once()
函数中。但是我无法访问变量
称为 whatever
。在写这个问题时,我还想我可以尝试将 firebase 数据直接设置为 data()
.
我的问题是我如何在 VueJS data() 函数中传递数据,以便当用户刷新或重新登录数据时填充这两个不同选项中的输入字段?
<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;
});
});
}
尝试以下内容,其中包含我评论中的更改。澄清一下,使用计算的 属性 来执行查询是理想的,因为它将在生命周期的某个时刻执行。
您也可以使用一个方法,但您必须在某个时候调用它 - 您在页面重新加载时提到,那么组件生命周期挂钩之一将是理想的。
下面是计算的 属性 方法。 属性 绑定到 v-model,因此 Vue 也可能会强制您也定义 setter,但这很简单。
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>
我知道 Firebase returns 数据是异步的,所以我实际上 将变量放在 once()
函数中。但是我无法访问变量
称为 whatever
。在写这个问题时,我还想我可以尝试将 firebase 数据直接设置为 data()
.
我的问题是我如何在 VueJS data() 函数中传递数据,以便当用户刷新或重新登录数据时填充这两个不同选项中的输入字段?
<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;
});
});
}
尝试以下内容,其中包含我评论中的更改。澄清一下,使用计算的 属性 来执行查询是理想的,因为它将在生命周期的某个时刻执行。
您也可以使用一个方法,但您必须在某个时候调用它 - 您在页面重新加载时提到,那么组件生命周期挂钩之一将是理想的。
下面是计算的 属性 方法。 属性 绑定到 v-model,因此 Vue 也可能会强制您也定义 setter,但这很简单。
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>