Typescript 如何从setup()函数返回反应变量?
我正在构建一个小型notes应用程序,并正在学习Vue3+打字脚本。下面的代码允许动态创建和显示注释数组(我希望我正确地对其进行了裁剪,代码下面有一般说明): 区别在于Typescript 如何从setup()函数返回反应变量?,typescript,vue.js,vuejs3,Typescript,Vue.js,Vuejs3,我正在构建一个小型notes应用程序,并正在学习Vue3+打字脚本。下面的代码允许动态创建和显示注释数组(我希望我正确地对其进行了裁剪,代码下面有一般说明): 区别在于 v-for迭代displayedNotes而不再是allNotes displayedNotes()是一种新方法 最终结果是什么都不显示,displayedNotes被创建,但是当allNotes增长时,它是空的 我应该如何返回displayedNotes以使其成为反应性的?您应该创建一个计算属性,如下所示: const f
迭代v-for
而不再是displayedNotes
allNotes
是一种新方法displayedNotes()
displayedNotes
被创建,但是当allNotes
增长时,它是空的
我应该如何返回
displayedNotes
以使其成为反应性的?您应该创建一个计算属性,如下所示:
const filteredNotes = computed(() => displayedNotes())
在这种情况下,displayedNotes()
以后可能会被重命名,在该函数中,您可以添加过滤逻辑。如果您的allNotes
发生更改,则将再次调用computed中的该函数并返回新的filteredNotes
您现在要做的只是将
filteredNotes
添加到您的返回对象中,并在v-for
循环中使用它,而不是allNotes
,以了解代码中哪些地方工作不正常。可能有两件事。在您的v-for
通话中,我想您需要调用displayedNotes()。2.您正在返回allNotes
,这是一个ref
。因此,您实际拥有的是一个代理
,您只返回该代理。您需要将.value
添加到您的返回所有备注中
谢谢。首先,我忘记了computed()
:/。谢谢你提醒我。然后我意识到我对.value
部分不太了解(我知道它,只是不太确定它到底应该用在哪里)——我会读下去。最后,随着这些变化,一切正常:)谢谢
<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>
const filteredNotes = computed(() => displayedNotes())