【问题标题】:Why does vue3 not re-render a ref of reactive variable when it's not deeply nested为什么 vue3 在嵌套不深的情况下不重新渲染反应变量的引用
【发布时间】: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


    【解决方案1】:

    我假设您发布的示例代码是一个人为的示例,因为它会产生运行时错误。在 JS 中,您不能重新分配给 const,您在示例代码中多次这样做。因此,我无法重现您声称看到的行为。

    要修复示例 A 和示例 B,您需要更改将响应分配给反应对象的方式。

    • 示例 A - 您正在使用 ref,您需要分配给 ref 的 value 属性 - results.value = response.data。有关更多信息,请参阅Vue docs on ref
    • 示例 B - 您不能重新分配给 reactive - 这是使用 reactive 的限制。如果 reactive 的值是一个对象,那么您可以使用 Object.assign 解决此问题(请参阅 https://stackoverflow.com/a/65733741/6767625),但由于您的值是一个数组,因此最好的解决方法是使用示例 C,正如您所说的那样有效美好的。

    【讨论】:

      猜你喜欢
      • 2017-04-03
      • 1970-01-01
      • 2017-04-03
      • 2017-03-25
      • 1970-01-01
      • 2021-01-19
      • 1970-01-01
      • 2020-09-05
      • 2023-02-16
      相关资源
      最近更新 更多