Emanon
Emanon

Reputation: 929

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

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?

Upvotes: 52

Views: 45865

Answers (1)

tony19
tony19

Reputation: 138526

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

Upvotes: 84

Related Questions