英文:
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)
<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>
what am I doing wrong? why menu?[0].disabled is not reactive?
答案1
得分: 2
disabled
在设置块中传递的是值,没有办法将 menu
与 disabled
这种方式关联起来,使得 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<[]>([{ disabled: false }]);
It should be:
const menu = reactive<[]>([{ disabled }]);
A ref is unwrapped when used inside reactive object, menu[0].disabled === disabled.value
.
答案2
得分: 1
以下是您要翻译的代码部分:
<script setup>
import { ref, reactive } from 'vue'
const disabled = ref(false);
const menu = reactive([
{
disabled
}
]);
</script>
<template>
{{disabled}}
<button @click="disabled = !disabled">
Toggle
<button>
<br>
{{menu[0]?.disabled}}
</template>
希望这能对您有所帮助。
英文:
Try this:
<script setup>
import { ref, reactive } from 'vue'
const disabled = ref(false);
const menu = reactive([
{
disabled
}
]);
</script>
<template>
{{disabled}}
<button @click="disabled = !disabled">
Toggle
</button>
<br>
{{menu[0]?.disabled}}
</template>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论