40
votes

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?

1
That second example should work just as you say, right? Have you tried? I can't check, on mobile atmkingdaro
@kingdaro When I simply use the prop name it's value is an empty string in my component.Emanon
Could you show the source for your component? Also, in your props definition, it should be lowercase type, not Type. Unless that's a typokingdaro
@kingdaro You're right. The capital T in type was messing it up and not making it a Boolean. Thank you.Emanon

1 Answers

65
votes

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