Inertia.js和Vue.js:Laravel SPA中嵌套组件渲染的React性问题

zzlelutf  于 2023-11-20  发布在  Vue.js
关注(0)|答案(1)|浏览(138)

我正在使用Inertia.js构建Laravel和Vue.js SPA。当我最初直接在主页中渲染todos时,数据会更新新创建的todos。然而,在引入TodoList组件来处理渲染后,添加新的待办事项后,数据未按预期更新TodoList组件接收todos prop,但在新数据可用时不会响应性地更新。
下面是代码的代码片段:
web.php:

Route::get('/', [TodoController::class, 'index'])->name('index');
Route::apiResource('todos', TodoController::class);

字符串
todoController.php:

class TodoController extends Controller
{
    //
    public function index()
    {
        return Inertia::render('Home', [
            'todos' => Todo::latest()->get()->toArray(),
        ]);
    }

    public function store(Request $request)
    {
        Todo::create([
            'task' => $request->input('task'),
        ]);

        return redirect()->to('/');

    }

}


Home.vue:

<template>
    <TodoList :todos="todos" />
</template>

<script setup>
import TodoList from "./TodoList.vue";

defineProps(["todos"]);
</script>


TodoList.vue:

<template>
    <div class="w-2/3 flex flex-col justify-center">
        <Todo v-for="todo in todos" :todo="todo" />
    </div>
</template>

<script setup>
import Todo from "./Todo.vue";

defineProps(["todos"]);
</script>


Todo.vue:

<template>
        <form @submit.prevent="addTodo" class="relative">
            <input
                class="p-3 pr-12 w-full rounded-md"
                type="text"
                name="todo"
                id="todo"
                placeholder="Create a new todo..."
                v-model="todoForm.task"
            />
            <button
                class="absolute text-white flex justify-center items-center top-1 right-1"
            >
                <span
                    class="text-white bg-indigo-600 rounded-full text-5xl h-10 w-10 leading-[30px]"
                    >+</span
                >
            </button>
        </form>
    </template>

    <script setup>
    import { useForm } from "@inertiajs/vue3";
    const todoForm = useForm({
        task: "",
    });

    const addTodo = () => {
        todoForm.post("/todos", {
            onSuccess: () => {
                todoForm.reset("task");
            },
        });
    };
    </script>


我尝试用“ref”React性API Package 作为props传递的todos,没有结果。

8yoxcaq7

8yoxcaq71#

这是一个简单的错误,我忘了给todos添加key属性。添加key将使TodoList更新新添加的todo。

相关问题