Joseph
Joseph

Reputation: 4725

Why Vue treats unspecified boolean props as false?

Please see this example

If I have a component like this:

<template>
  <div v-if="on">
    Hello
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    on: Boolean
  },
  mounted() {
    console.log(this.on)
  }
};
</script>

And then I render that component and specify nothing on the prop

<template>
  <div >
    <HelloWorld/>
  </div>
</template>

This will output false instead of undefined?

Why is that?

Is there anyway I can detect if people didn't specify the prop, so I can use lodash _.isBoolean to detect it?

Currently, the only way I know is manually set the default to undefined.

Upvotes: 0

Views: 743

Answers (1)

Qonvex620
Qonvex620

Reputation: 3972

You could set a default value on it and check if the value is still the same then the user didn't pass a prop, but there are instance where you can't really compare your value to its default, like if the prop is a function.

You could have this.$options.propsData inside of your component. If the prop is present here, the user has explicitly set it; default values aren't shown in.

Upvotes: 1

Related Questions