【发布时间】:2023-01-31 01:14:38
【问题描述】:
我想了解 Vue 3 中的 Composition-API Reactive。我想构建一个搜索栏,它会立即显示模板中的结果。
为此,我有一个反应变量搜索和一个反应变量结果。
如果我将结果声明为 ref() 应该自动转换为 reactive() 因为它是一个数组 [EXAMPLE A] 或者直接将此数组声明为 reactive() [EXAMPLE B] 结果不会直接在模板中呈现。我写了一个字母,没有任何反应,但是当我写第二个字母时,我看到了之前用单个字母搜索的结果。
当我深入嵌套结果 [EXAMPLE C] 时,它起作用了,我立即看到所有结果。
这是为什么?我不明白为什么 A 或 B 不起作用。
<script setup>
let search = ref("");
// EXAMPLE A
// This does not work, the search results are shown one "tick" later
const results = ref([]);
// EXAMPLE B
// This does not work, the search results are shown one "tick" later
const results = reactive([]);
// EXAMPLE C
// This does work, when the result array is deeply-nested in a reactive object
const query = reactive({ results: [] });
watch(search, (value) => {
axios
.post("/search", { search: value })
.then(response => {
// EXAMPLE A / B
results = response.data;
// EXAMPLE C
query.results = response.data;
})
.catch();
});
</script>
<template>
<!-- EXAMPLE A / B -->
<div v-for="product in results" :key="product.id">
<div>{{ product.id }}</div>
<div>{{ product.name }}</div>
</div>
<!-- EXAMPLE C -->
<div v-for="product in query.results" :key="product.id">
<div>{{ product.id }}</div>
<div>{{ product.name }}</div>
</div>
</template>
【问题讨论】:
标签: javascript laravel vue.js axios