【发布时间】:2021-06-04 12:02:28
【问题描述】:
我正在构建一个小笔记应用程序,并且正在学习 Vue3 + Typescript。下面的代码允许动态创建和显示一个笔记数组(我希望我把它修剪得正确,代码下面是一般描述):
<template>
<q-layout>
<div
v-for="note in allNotes"
class="note q-ma-sm q-gutter-sm"
:id="note.id"
>
<q-editor
v-model="note.text"
>
</q-editor>
</div>
<q-page-sticky position="bottom-right" :offset="[18, 18]">
<q-btn fab icon="add" color="accent" @click="addNewNote"/>
</q-page-sticky>
</q-layout>
</template>
<script lang="ts">
import {defineComponent, ref} from 'vue'
export default defineComponent({
name: 'App',
components: {},
setup() {
// a single note
interface Note {
id: number
creationDate: string
text: string
tags: string[]
deleted: boolean
isFocused: boolean
}
// all the notes in the app
let allNotes = ref<Note[]>([])
function addNewNote() {
const now = new Date()
allNotes.value.push({
creationDate: now.toISOString(),
deleted: false,
id: now.getTime(),
tags: [],
text: "",
isFocused: false
})
}
function displayedNotes() {
return allNotes
}
return {
allNotes,
addNewNote,
}
}
});
</script>
<style lang="scss">
</style>
这个想法是allNotes 保存笔记,这些笔记显示在v-for 循环中。
我想做一个小的修改,预计要显示的注释将被过滤,为此我创建了一个方法displayedNotes,它应该简单地返回allNotes(稍后会有一些过滤发生在那里)
<template>
<q-layout>
<div
v-for="note in displayedNotes"
class="note q-ma-sm q-gutter-sm"
:id="note.id"
>
<q-editor
v-model="note.text"
>
</q-editor>
</div>
<q-page-sticky position="bottom-right" :offset="[18, 18]">
<q-btn fab icon="add" color="accent" @click="addNewNote"/>
</q-page-sticky>
</q-layout>
</template>
<script lang="ts">
import {defineComponent, ref} from 'vue'
export default defineComponent({
name: 'App',
components: {},
setup() {
// a single note
interface Note {
id: number
creationDate: string
text: string
tags: string[]
deleted: boolean
isFocused: boolean
}
// all the notes in the app
let allNotes = ref<Note[]>([])
function addNewNote() {
const now = new Date()
allNotes.value.push({
creationDate: now.toISOString(),
deleted: false,
id: now.getTime(),
tags: [],
text: "",
isFocused: false
})
}
function displayedNotes() {
return allNotes
}
return {
allNotes,
displayedNotes,
addNewNote,
}
}
});
</script>
<style lang="scss">
</style>
区别是
-
v-for迭代displayedNotes而不是allNotes了 -
displayedNotes()是一种新方法。
最终结果是什么都没有显示,displayedNotes 被创建,但当allNotes 增长时为空。
我应该如何返回 displayedNotes 以使其具有反应性?
【问题讨论】:
标签: typescript vue.js vuejs3