【问题标题】:Vue 3 Composition API, Props, and v-if rendering despite false valueVue 3 Composition API、Props 和 v-if 渲染,尽管值为 false
【发布时间】:2021-09-15 18:06:22
【问题描述】:

我有一个问题,我认为我在这里并没有真正理解。我有一个包含一个子组件,它传递一个“活动”道具,可以设置为真或假。这个想法是,如果它被传递为“true”,那么组件的一部分就会显示,如果它被传递为“false”,它不会。

据我了解,我应该能够只使用道具名称并执行以下操作:

<template>
   <div v-if="active">this is the value of active: {{active}}</div>
</template>

这里的问题是,如果我在上面的语句中直接将 v-if 设置为 true 或 false,那么它会按预期工作。如果我将它作为道具传递,它总是显示,无论是真是假。

有效(不显示任何内容):

<template>
   <div v-if="false">this is the value of active: {{active}}</div>
</template>

不起作用(无论 active 的值如何,div 中的内容都会显示):

//-File1---------------------------------------

<template>
   <myComponent active=false />
</template>

//-File2---------------------------------------

<template>
   <div v-if="active">this is the value of active: {{active}}</div>
</template>

<script>
    export default{
        props:['active']
    }
</script>

这是为什么?我通过显示“活动”的值来确认它传入为假,但尽管值为假,但它仍在呈现。我在这里错过了什么吗?我尝试过使用引号,不使用引号,使用 ref 将其传递到本地值并使用它:

import { ref } from 'vue';

export default{
    props:['active']
    setup(props,ctx){
        const active = ref(props.active);
        return {
            active
        }
    }
}

那也没用。

【问题讨论】:

    标签: javascript vue.js vue-component vuejs3 vue-props


    【解决方案1】:

    这是因为您的 prop 是作为字符串从父组件传入的(与所有其他 html 属性一样的默认行为)。为了将 prop 作为布尔值传递,您需要使用 v-bind 语法或简称 :,以便将 false 评估为 javascript 表达式字符串:

    <template>
       <myComponent v-bind:active="false" />
    </template>
    

    或者

    <template>
       <myComponent :active="false" />
    </template>
    

    【讨论】:

    • 没问题。我不认为这只是你。每个开始使用 Vue 的人都偶然发现了它。
    【解决方案2】:

    在您的导出默认设置上,

    props: {
        active: {
          type: Boolean,
          default: false
        }
    }
    

    在您的组件模板上,

    <template>
       <div v-if="active !== false"> show only when active {{ active }}</div>
    </template>
    

    使用组件时,将活动元素绑定为false

    <myComponent :active="false" />
    

    【讨论】:

      猜你喜欢
      • 2021-10-25
      • 2021-06-24
      • 2021-10-14
      • 2022-10-06
      • 2017-09-09
      • 2020-06-16
      • 2020-09-06
      • 2018-12-03
      • 1970-01-01
      相关资源
      最近更新 更多