Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 415
Emanon Avatar asked Mar 10 '18 11:03

Emanon


People also ask

How do props work in Vue?

What are props? In Vue, props (or properties), are the way that we pass data from a parent component down to it's child components. When we build our applications out of components, we end up building a data structure called a tree.

Are Vue props read only?

Another thing to keep in mind is that Props are read-only and cannot be modified by the child component because the parent component "owns" that value. Let's balance things up now – the parent components pass props to the child component(s) while the child component emit events to the parent component(s).

Are Props passed by reference Vue?

Vue does not take a copy when you pass objects via props. If you pass an object via a prop then both components will be seeing the same object. As it's the same object, any property changes made by the child will also impact the other parent.

Are props required by default Vue?

All props are optional by default, unless required: true is specified. An absent optional prop other than Boolean will have undefined value. The Boolean absent props will be cast to false .


1 Answers

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

like image 121
tony19 Avatar answered Sep 22 '22 07:09

tony19