I'm currently working on a small notes app and using Vue3 + Typescript to enhance my skills. The following code snippet demonstrates how to dynamically create and display an Array of notes:
<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() {
// defining the structure of a single note
interface Note {
id: number
creationDate: string
text: string
tags: string[]
deleted: boolean
isFocused: boolean
}
// storing 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>
The main concept here is that allNotes
contains the notes which are shown using a v-for
loop.
I decided to make a minor change by assuming that the displayed notes will be filtered in the future. For this purpose, I introduced a method called displayedNotes
which for now simply returns allNotes
(filtering functionality will be added later).
<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() {
// defining the structure of a single note
interface Note {
id: number
creationDate: string
text: string
tags: string[]
deleted: boolean
isFocused: boolean
}
// storing 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>
The changes made include:
v-for
now loops overdisplayedNotes
instead ofallNotes
.displayedNotes()
has been introduced as a new method.
As a result, no content is displayed, since although displayedNotes
is created, it remains empty when allNotes
grows.
How can I ensure that displayedNotes
remains reactive?