[Vuejs]-Creating a conditional input field component in Vue

2👍

Let’s take this as an example:

<VInputField label="User Password" password :defaultvalue="'myPass'"/>

After checking the console, we can see that passing password(when its prop type is String) is not enough.

props: {
 /* ... */
 password: {
   type: String
  }
},

created () {
 console.log(this.$props);
 /*
  ...
  password: ""
  ...
 */
}

An empty string(“”, ”) evaluates to false.

I can think of one approach, by making the prop’s type Boolean:

password: {
   type: Boolean
}
  • <VInputField label="User Password" :password="true" :defaultvalue="'myPass'"/>

Here is a CodeSanbox example.

Edit

By passing password this way
<VInputField label="User Password" password :defaultvalue="'myPass'"/>
you will always get a true value(if the prop’s type is also Boolean).

2👍

v-else-if="password" tests the value of the password prop. It is equivalent to:

if (vm.password)

However,

<InputField label="User Password" password :defaultvalue="myPass" />

provides the password prop, but without a value which is the same as :password="true". However, the password prop requires a string, not a boolean. In that case, Vue apparently assigns the empty string to the prop which evaluates to false. It’s the same with all your other examples which is why the else clause is always chosen.

By the way, you should have warnings in the console regarding this. You shouldn’t ignore those.

This should work:

<InputField label="User Password" password="true" :defaultvalue="myPass" />

However, I suggest you rework your component. Instead of having so many props defined, have a single one called inputType and pass the desired input type as a string. Then you would have:

<InputField label="User Email" inputType="email" :defaultvalue="myEmail" />
<InputField label="User Password" inputType="password" :defaultvalue="myPass" />
👤bernie

Leave a comment