Can a Vue Boolean prop be true by its presence and false by its absence?

Emanon picture Emanon · Mar 10, 2018 · Viewed 28.5k times · Source

In my Vue component, I have a Boolean prop called "obj", defined like this:

obj: { Type:Boolean, default: false}

I can set it to true like this:

<my-component :obj="true"></my-component>

However, I'd like to be able to set it to true like this:

<my-component obj></my-component>

I'd like the presence of the prop to mean true and its absence to mean false. Is there a way to define a prop that works this way in a Vue component?

Answer

tony19 picture tony19 · Mar 10, 2018

That's the behavior of a Boolean prop in any case. You simply define the prop as:

{
  props: {
    fast: Boolean
  }
  ...
}

And it defaults to false. When you specify the attribute at all in the following template, it is set to true:

<my-foo fast/>  <!-- fast is true -->

demo