我正在尝试重新配置Vue.js Workflowy克隆以使用Firebase存储列表项。克隆基于以下存储库:https://github.com/9diov/myflowy。此存储库可将列表项组织到列表树中。列表项可以左右移动,以确定它们与父级列表项的关系。我成功实现了将列表项及其级别添加到Firebase的addItem函数。我现在正在尝试实现一种从数据库中检索项目并将其返回到模板的方法。到目前为止,我已经能够建立一个beforeCreate()
生命周期挂钩来检索列表项的值和级别并将它们推入列表数组。我添加了console.log(this.list)
,以确认数据已添加到数组中。但是,列表值及其级别不会显示在屏幕上。我如何beforeCreate()
进行钩挂才能将存储在Firebase中的value
和level
返回到树形列表?
这是我的组件:
<template>
<div id="app">
<span>{{ msg }}</span>
<ul>
<li v-for="(item, index) in list"
v-bind:class="item.level">
<span>•</span>
<input
v-model="item.value"
@keydown.down.prevent="moveDown"
@keydown.up.prevent="moveUp"
@keydown.tab.prevent="shiftRight(index, $event)"
@keydown.shift.tab.prevent="shiftLeft(index, $event)"
@keydown.enter.prevent="addItem(index)"
v-focus="index === focused"
@focus="focused = index"
@blur="focused = null">
</li>
</ul>
</div>
</template>
<script>
import { fblist } from './firebase'
import { focus } from 'vue-focus';
import Vue from 'vue';
const MAX_LEVEL = 10;
export default {
name: 'app',
directives: { focus: focus },
data () {
return {
msg: 'Welcome to Your Vue.js App',
list: [
{ value: 'new item', level: 0 }
],
focused: null
}
},
async created () {
let snapshot = await fblist.get()
const list = []
snapshot.forEach(doc => {
let appData = doc.data()
appData.id = doc.id
// this.list.push(appData)
this.list.push({ value: appData.value, level: appData.level })
console.log(this.list)
})
this.list = list
},
methods: {
moveDown: function() {
this.focused = Math.min(this.focused + 1, this.list.length - 1);
},
moveUp: function () {
this.focused = Math.max(this.focused - 1, 0);
},
shiftLeft: function (index, event) {
let self = this;
self.list[index].level = Math.max(self.list[index].level - 1, 0);
},
shiftRight: function (index, event) {
if (event.shiftKey)
return;
if (index === 0) return;
this.list[index].level = Math.min(this.list[index].level + 1, this.list[index - 1].level + 1, MAX_LEVEL);
},
async addItem (index) {
this.list.splice(index + 1, 0, {value: '', level: this.list[index].level});
this.focused = index + 1;
await fblist.add({
listItem: this.list
})
// this.getData()
}
}
}
</script>
创建了()钩子
async created () {
let snapshot = await fblist.get()
const list = []
snapshot.forEach(doc => {
let appData = doc.data()
appData.id = doc.id
this.list.push({ value: appData.value, level: appData.level })
console.log(list)
})
this.list = list
},
答案 0 :(得分:0)
beforeCreate
挂钩在组件初始化时运行:数据尚未被响应,并且事件尚未设置。看看https://vuejs.org/v2/api/#beforeCreate和https://vuejs.org/v2/guide/instance.html#Lifecycle-Diagram。
使用created
挂钩来获取Firestore数据库(或任何其他API)是相当“标准”的。在此挂钩中,您将能够访问反应性数据。
所以只需修改
async beforeCreate () {
//.....
}
到
async created () {
//.....
}