![](/img/trans.png)
[英]Reactive data in vue composition api is not rendered in template
[英]Vue 3 composition API data is not reactive
我有一個簡單的應用程序,其中有一個用於添加任務的組件和我想顯示所有添加任務的主頁。 問題是,當我添加一個新任務時,它不會顯示在我渲染所有任務的模板中。 我想重新使用我的 AddTasks 組件和 useTasks 組合函數來添加任務。 但它們沒有出現在主頁上。 我究竟做錯了什么?
這是要克隆並嘗試的存儲庫:
$ git clone https://github.com/martinszeltins/vue3-reactivity.git
$ cd vue3-reactivity
$ npm install
$ npm run serve
這是我的App.vue
<template>
<div v-for="task in tasks">
{{ task }}
</div>
<add-task />
</template>
<script>
import AddTask from './components/AddTask.vue'
import useTasks from './composition/useTasks.js'
export default {
components: {
AddTask
},
setup() {
const { tasks } = useTasks()
return { tasks }
},
}
</script>
這是AddTask組件
<template>
<button @click="addTask">
Add new task
</button>
</template>
<script>
import useTasks from '../composition/useTasks.js'
export default {
setup()
{
const { add } = useTasks()
function addTask() {
add('My new task')
}
return { addTask }
}
}
</script>
和useTasks組合函數
import { ref } from 'vue'
export default function useTasks() {
const tasks = ref(['First task'])
function add(task) {
alert(`Adding task - ${task}`)
tasks.value.push(task)
}
return { tasks, add }
}
這是因為每次函數運行時您的數組都會被重置。
將它移到函數之外,它應該可以工作:
import { ref } from 'vue';
const tasks = ref(['First task']);
export default function useTasks() {
function add(task) {
alert(`Adding task - ${task}`);
tasks.value.push(task);
}
return { tasks, add };
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.