Reputation: 729
I want to put a directive in a Vue component on condition. I have installed a package called "mask" and I want to put v-mask directive on condition.. in some situations component has no property called "mask" but in some situations has. so I get this error when I don't pass mask to my component this is the component that I use v-mask directive in :
<input v-mask="mask" />
is there any way that I could insert v-mask if the mask attribute passed and don't if mask is empty ????
Upvotes: 5
Views: 4299
Reputation: 1406
You could check for the condition before binding the directive.
Consider your use case:
<input v-mask="mask" />
Your directive would look like this:
import { mask } from 'v-mask'
directives: {
mask: {
bind(el, binding, vnode, oldVnode) {
// This is the condition
if (binding.value) {
mask(el, binding, vnode, oldVnode)
}
}
},
},
The condition in the bind() method checks if the value passed to the directive exists, if it's true-ish.
If it is true-ish, it goes on to execute the actual directive.
Upvotes: 6
Reputation: 375
You can use computed item here;
var vm = new Vue({
el: '#example',
data: {
mask: 'maskdata'
},
computed: {
IsMaskEmpty: function () {
return this.mask === "";
}
}
})
after compute a bool result with IsMaskEmpty
function, you can create DOM element as you want with this condition.
<input v-mask="mask" v-if="!IsMaskEmpty">
<input v-if="IsMaskEmpty">
Upvotes: 1
Reputation: 3719
<input v-mask="mask" v-if="mask.length">
<input v-else>
Upvotes: 6