Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put a Vue directive on condition

Tags:

vue.js

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 ????

like image 448
Hamid Avatar asked Jan 02 '23 00:01

Hamid


1 Answers

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.

like image 107
rfarias Avatar answered Jan 05 '23 15:01

rfarias