简体   繁体   中英

Vue 3 Composition API, Props, and v-if rendering despite false value

I have an issue I don't think I'm really understanding here. I have a child component included which passes an "active" prop in and can be set to true or false. The idea is if it's passed "true" then a part of the component shows, and if it's passed "false" it doesn't.

from what I understand, I should be able to just use the prop name and do something like:

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

The issue here is if I directly set v-if in the above statement to true or false, then it works as expected. If I pass it in as a prop, it always shows regardless of whether true or false.

Works (doesn't show anything):

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

Doesn't Work (contents in the div shows regardless of value of active):

//-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>

Why is this? I confirmed, by displaying the value of "active" that it's passing in as false, but it's still rendering despite the value being false. Am I missing something here? I've tried playing with quotes, without quotes, passing it into a local value using ref and using that:

import { ref } from 'vue';

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

that also did not work.

It's because your prop is passed in as string from parent component (the default behavior like all other html properties). In order to pass in the prop as boolean, you need to use v-bind syntax or : for short so that false is evaluated as a javascript expression instead of string:

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

Or

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

on your export default,

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

on your component template,

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

when using the component, bind the active element to false

<myComponent :active="false" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM