我正在尝试使用for循环引用firebase数据库的子节点。我正在使用Vue和Vue-fire。问题是,在以下代码中,categories[addItem.category]
未引用正确的数据。
<el-select v-model="addItem.category" placeholder="Select a category." id="category-select">
<el-option
v-for="(val, key) in categories"
:key="val['.key']"
:label="val['.key']"
:value="val['.key']">
</el-option>
</el-select>
<el-button @click="showAdd=true">new category</el-button>
<el-select v-model="addItem.subcategory" placeholder="Select a subcategory." id="subcategory-select" v-show="addItem.category!=''">
<el-option
v-for="subcat in categories[addItem.category]"
:key="subcat['.key']"
:label="subcat['.key']"
:value="subcat">
</el-option>
</el-select>
<el-button v-show="addItem.category!=''" @click="showAdd=true">add subcategory</el-button>
我正在尝试获取所选类别的所有键,如果选择“机械”,则应提供“机械”。目前,选择“机械”会使categories[addItem.category]
等于undefined
。以下是我的数据库中的数据:
[![在此处输入图像说明] [1]] [1]
有谁可以告诉我为什么我的firebase引用categories[addItem.category]
没有引用子值?
如果有帮助,这就是我保存数据的方式:
methods: {
add(){
var updates = {};
if (this.addItem.category==''){
updates['/' + this.addItem.text + '/'] = "null";
}
else if (this.addItem.subcategory==''){
console.log('adding a subcategory: ' + this.addItem.subcategory);
console.log(this.addItem.category + ' is the category name');
updates['/' + this.addItem.category + '/' + this.addItem.text + '/'] = "null";
}
db.ref('categories').update(updates).then((successMessage) => {
// successMessage is whatever we passed in the resolve(...) function above.
// It doesn't have to be a string, but if it is only a succeed message, it probably will be.
console.log("Yay! " + successMessage);
});
其中引用了以下数据:
data(){ return {
addItem: {
open: false,
count: 0,
category: '',
subcategory: '',
kks: {
name: ''
},
document: {
name: ''
},
product: {
name: ''
},
text: ''
},
}}
}
这里是firebase属性:
firebase: function(){
return {
categories: db.ref('categories')
}
}
[1]: https://i.stack.imgur.com/hYZN6.png
答案 0 :(得分:2)
这就是我最终做的事情。以下是作为计算属性添加的:
subcategories: function(){
if (this.addItem.category){
var val;
db.ref('categories/' + this.addItem.category).on('value', function(snapshot){
val = snapshot.val();
});
return val;
}
return this.categories;
}