Vue3: 深层响应

huangapple go评论46阅读模式
英文:

Vue3: deep reactivity

问题

<script setup>
import { ref, reactive } from 'vue'

const disabled = ref(false);

const menu = reactive<[]>([
{
disabled: disabled.value
}
]);
</script>

<template>

{{disabled}}
<button @click="disabled = !disabled">
Toggle
</button>

<br>
{{menu[0]?.disabled}}
</template>
您的代码如下所示,主要问题是menu[0]?.disabled不是响应式的。

英文:

So I have a very simple scenario that I cannot make it work (find the code in the vue playground)

&lt;script setup&gt;
import { ref, reactive } from &#39;vue&#39;

const disabled = ref(false);

const menu = reactive&lt;[]&gt;([
  {
    disabled: disabled.value
  }
 ]);
&lt;/script&gt;

&lt;template&gt;
  
  {{disabled}}
  &lt;button @click=&quot;disabled = !disabled&quot;&gt;
    Toggle
  &lt;/button&gt;
  
  &lt;br&gt;
  {{menu[0]?.disabled}}
&lt;/template&gt;

what am I doing wrong? why menu?[0].disabled is not reactive?

答案1

得分: 2

disabled 在设置块中传递的是值,没有办法将 menudisabled 这种方式关联起来,使得 disabled.value === false 与以下方式效果相同:

const menu = reactive([][{ disabled: false }]);

应该是:

const menu = reactive([][{ disabled }]);

在反应性对象内部使用 ref 时,会取消引用,menu[0].disabled === disabled.value

英文:

disabled is passed by value in setup block, there is no way how menu could be associated with disabled this way, that disabled.value === false makes this efficiently the same as:

const menu = reactive&lt;[]&gt;([{ disabled: false }]);

It should be:

const menu = reactive&lt;[]&gt;([{ disabled }]);

A ref is unwrapped when used inside reactive object, menu[0].disabled === disabled.value.

答案2

得分: 1

以下是您要翻译的代码部分:

&lt;script setup&gt;
import { ref, reactive } from &#39;vue&#39;

const disabled = ref(false);

const menu = reactive([
  {
    disabled
  }
 ]);
&lt;/script&gt;

&lt;template&gt;
  
  {{disabled}}
  &lt;button @click=&quot;disabled = !disabled&quot;&gt;
    Toggle
  &lt;button&gt;
  
  &lt;br&gt;
  {{menu[0]?.disabled}}
&lt;/template&gt;

希望这能对您有所帮助。

英文:

Try this:

&lt;script setup&gt;
import { ref, reactive } from &#39;vue&#39;

const disabled = ref(false);

const menu = reactive([
  {
    disabled
  }
 ]);
&lt;/script&gt;

&lt;template&gt;
  
  {{disabled}}
  &lt;button @click=&quot;disabled = !disabled&quot;&gt;
    Toggle
  &lt;/button&gt;
  
  &lt;br&gt;
  {{menu[0]?.disabled}}
&lt;/template&gt;

Сode in the vue playground

Docs

huangapple
  • 本文由 发表于 2023年4月10日 18:46:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75976416.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定