Joseph
Joseph

Reputation: 4725

Why passing empty string to Vue component Boolean props considered truthy?

Please see this minimum example, I have a simple component like this

HelloWorld.vue

<template>
  <div v-if="show">I will show even if show prop is passed as empty string</div>
</template>

<script>
  export default {
    props: {
      show: Boolean,
    },
  };
</script>

Now, If I do this to that component

App.vue

<template>
  <div>
    <HelloWorld :show="show" />
  </div>
</template>

<script>
  import HelloWorld from "./components/HelloWorld";

  export default {
    data() {
      return {
        show: "",
      };
    },
    components: {
      HelloWorld,
    },
  };
</script>

It will render out that string!

Why is this happening?

An empty string is considered falsy but is truthy in the Vue component, that's quite weird.

I probably get why it does this way because now you are enabled to do this

<template>
  <div>
    <!-- you can just write show -->
    <HelloWorld show />
  </div>
</template>

However, I think the template-compiler should do this thing because take a look at JSX

enter image description here

It supports the shorthand at compiler level, so I was wondering why Vue design like this.

Upvotes: 6

Views: 2909

Answers (1)

ElTs
ElTs

Reputation: 74

Vuejs use Boolean props as in HTML, where empty string will be considered as true

They wrote it in their documentation

Upvotes: 6

Related Questions