Home  >  Q&A  >  body text

Vue 3 Composition API: Render Props and v-if even if value is False

I've run into a problem here that I feel like I don't really understand. I include a child component that is passed a prop called "active" which can be set to true or false. The idea is that if "true" is passed, then part of the component will be displayed, if "false" is passed, it will not be displayed.

From my understanding, I should be able to just use the prop name, like this:

<template>
   <div v-if="active">这是active的值:{{active}}</div>
</template>

The problem is that if I directly set the v-if in the above statement to true or false, then it works as expected. If I pass it in as a prop, whether true or false, it always displays.

Valid (display nothing):

<template>
   <div v-if="false">这是active的值:{{active}}</div>
</template>

Invalid (no matter what the value of active is, the content in the div will be displayed):

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

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

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

<template>
   <div v-if="active">这是active的值:{{active}}</div>
</template>

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

Why is this? I confirmed it by showing the value of "active" and it was passed the value false, but it still renders despite the value being false. Am I missing something here? I've tried with quotes, without quotes, using ref to pass it a local value and using it:

import { ref } from 'vue';

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

This didn't work either.

P粉786432579P粉786432579348 days ago749

reply all(2)I'll reply

  • P粉976488015

    P粉9764880152023-11-06 10:51:02

    On your export defaults,

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

    On your component template,

    <template>
       <div v-if="active !== false"> 仅在 active 为真时显示 {{ active }}</div>
    </template>

    When using components, bind the active element to false

    <myComponent :active="false" />

    reply
    0
  • P粉327903045

    P粉3279030452023-11-06 09:00:36

    This is because your prop is a string passed from the parent component (same as the default behavior of other HTML attributes). In order to pass a prop as a boolean, you need to use the v-bind syntax or the : shorthand so false will be parsed as a JavaScript expression instead of string:

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

    or

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

    reply
    0
  • Cancelreply