3

我有以下包含这两个组件的待办事项应用程序:AppTodo

应用程序.vue

<template>
  <div class="todo-list">
    <div :key="index" v-for="(todo, index) in state.todos">
      <Todo :todo="todo" :state="state" />
    </div>
  </div>
</template>

<script>
import { reactive } from '@vue/composition-api';
import Todo from './components/Todo.vue';

export default {
  components: {
    Todo
  },
  setup() {
    let state = reactive({
      todos: [
        { text: 'Learn about Vue', isCompleted: false },
        { text: 'Meet friend for lunch', isCompleted: false },
        { text: 'Build really cool todo app', isCompleted: false }
      ]
    });

    return { state };
  }
};
</script>

待办事项

<template>
  <div class="todo">{{ todo.text }}<button @click="deleteTodo">x</button></div>
</template>

<script>
export default {
  props: ['todo', 'state'],
  setup({ todo, state }) {
    const deleteTodo = () => {
      state.todos = state.todos.filter(t => t != todo);
    };

    return {
      deleteTodo
    };
  }
};
</script>

deleteTodo函数在Todo.vue组件中运行良好,但是,我想知道是否可以不传递state对象而是使用ref()类似的对象并传递 todos...

所以在App.vue

//...
    let todos = ref({[
        { text: 'Learn about Vue', isCompleted: false },
        { text: 'Meet friend for lunch', isCompleted: false },
        { text: 'Build really cool todo app', isCompleted: false }
      ]);
//...

代替:

//...
   let state = reactive({
      todos: [
        { text: 'Learn about Vue', isCompleted: false },
        { text: 'Meet friend for lunch', isCompleted: false },
        { text: 'Build really cool todo app', isCompleted: false }
      ]
    });
//...

但是,当我尝试这样做时......孩子无法过滤已删除的待办事项并重新分配给todos变量。这行不通。

有什么想法可以让它工作ref吗?

4

1 回答 1

0

您以错误的方式使用 ref 。ref表示与响应式原始值一起使用,例如numbersstring,而reactive表示用于响应式对象。

您也可以将数组与 ref 一起使用。但是您不应该将数组包装在要在内部使用的对象中ref

正确的说法是

let todos = ref([      
        { text: 'Learn about Vue', isCompleted: false },
        { text: 'Meet friend for lunch', isCompleted: false },
        { text: 'Build really cool todo app', isCompleted: false }
    ])

然后你可以像你一样过滤。只是现在您必须引用数组,例如todos.value. 你已经在做state变量了。

https://v3.vuejs.org/guide/reactivity-fundamentals.html#declaring-reactive-state

于 2022-02-07T08:03:47.933 回答