Vue.js Setting Boolean Prop Defaults


Vue.js

Vue.js Boolean Prop Defaults

Vue.js is great.  Simple, quick and to the point.  But, I struggled with this issue for a while trying to get this to work and figured I would share.  It would “appear” to work, then not behave as I would expect.  It was as if a gremlin was in the works.  I moved the element from props into the Data region and it worked every time (other than the fact that I couldn’t set it as a prop, of course) which lead me to dig deeper and then onto what I found.  Can you say, Duh?

The magic sauce, which may be obvious to others, was to not simply set the value, but initialize it as an object:

The Wrong Way

What I had was this: (this code does NOT work)

props: {
  cardTitle: "uninitialized",
  isSmallCard: true
}

Evidently, this is not enough as isSmallCard would not ever be set to TRUE.
So, the moment you have been waiting for;
This is the “correct” way to set a default prop. (as far as I can determine, anyway) and likely valid for ALL defaults (with the proper type, of course)

The Right Way

props: {
  cardTitle: "uninitialized",
  isSmallCard: {
    type: Boolean,
    default: true
  }
}

Also, an item to note here is that props don’t map to Data, only the Vue instance – and in fact, props overwrite the “Data” keys.

This was a rather obscure piece of information to find. Perhaps it was just me.

Now, using the above method to establish defaults,  it seems obvious, despite the piles of sample code that show the first method of setting “defaults”.  At some point I may dig deeper into this issue. If you happen to have more information, please share by leaving a comment.

Happy Computing.
Wolf Scott, IOIHAN Development
www.ioihan.com

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.