gpt4 book ai didi

vue.js - 如果 Vue 3 引用是对象的属性,则它们的行为会有所不同

转载 作者:行者123 更新时间:2023-12-02 01:51:18 26 4
gpt4 key购买 nike

在使用 Vue 3 的 Composition API 时,我注意到模板引用在作为对象属性访问时的行为不同。我认为这最好总结为 this example in the SFC Playground ,但这是关键代码(来自单个文件组件):

    <script>
import { ref } from 'vue';
export default {
setup() {
const wut = ref(false);
const obj = { wut };
return {
wut,
obj,
};
},
};
</script>

<template>
<!-- obj.wut - false -->
<h3>obj.wut - {{ obj.wut }}</h3>
<!-- !!obj.wut - true -->
<h3>!!obj.wut - {{ !!obj.wut }}</h3>
<!-- obj.wut.value - false -->
<h3>obj.wut.value - {{ obj.wut.value }}</h3>
<!-- !!obj.wut.value - false -->
<h3>!!obj.wut.value - {{ !!obj.wut.value }}</h3>
<!-- does display -->
<h3 v-if="obj.wut">display logic for this: v-if="obj.wut"</h3>
<!-- does not display -->
<h3 v-if="!obj.wut">display logic for this: v-if="!obj.wut"</h3>
<!-- typeof obj.wut - object -->
<h3>typeof obj.wut - {{ typeof obj.wut }}</h3>
</template>

谁能解释为什么它在某些情况下似乎将 ref 视为对象,而在其他情况下解释其值?这是错误还是设计使然?

最佳答案

简短回答:这是设计的

长答案:

请查看Vue3 Guide -> Advanced Guides -> Reactivity -> Reactivity Fundamentals -> Ref unwrapping

Ref Unwrapping

When a ref is returned as a property on the render context (the object returned from setup()) and accessed in the template, it automatically shallow unwraps the inner value. Only the nested ref will require .value in the template:

在您的示例模板中,obj.wut 是一个 ref 对象,wut 是一个展开的原始值( bool 值)

额外内容:

  1. 在您的示例中,obj.wut 在页面中呈现为 false,似乎它在没有 .value 的情况下也能正常工作。那是因为 toDisplayString function在 vue 中,它获取 ref 对象 (obj.wut),它对 ref 对象的内部值执行 JSON.stringify。如果 wut 的值是 a string (const wut = ref('a string');),你会看到额外的双引号它在呈现的页面中,如 "a string"
  2. 文档中还有另一个提示,您可以将对象包装在 reactive (const obj = reactive({ wut })) 中以访问未包装的值在模板中。

关于vue.js - 如果 Vue 3 引用是对象的属性,则它们的行为会有所不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70310478/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com