【问题标题】:Vue 3 refs behave differently if they are the property of an object如果 Vue 3 refs 是对象的属性,则它们的行为会有所不同
【发布时间】:2022-01-15 11:57:26
【问题描述】:

在使用 Vue 3 的 Composition API 时,我注意到在模板 refs 内部,当它们作为对象的属性被访问时,它们的行为会有所不同。我认为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 视为一个对象并在其他情况下解释它的值?这是一个错误,还是设计使然?

【问题讨论】:

    标签: vue.js vuejs3 vue-composition-api


    【解决方案1】:

    简短回答:这是设计

    长答案:

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

    引用展开

    当 ref 作为渲染上下文(从 setup() 返回的对象)上的属性返回并在模板中访问时,它会自动浅层展开内部值。只有嵌套的 ref 需要模板中的 .value

    在您的示例模板中,obj.wut 是一个 ref 对象,wut 是一个未包装的原始值(布尔值)

    附加:

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

    【讨论】:

      猜你喜欢
      • 2020-06-10
      • 1970-01-01
      • 1970-01-01
      • 2011-11-06
      • 1970-01-01
      • 2022-01-22
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多