Home » vue » Vue – directive bind doesn't work on element refresh

Vue – directive bind doesn't work on element refresh

Posted by: admin November 26, 2021 Leave a comment

Questions:

I use vue.js to generate forms – all fields are in javascript objects array in structure like:

{
    type: "input",
    mask: "date",
    default: "2018/04/14"
},
{
    type: "input",
    mask: "currency",
    default: "0"
}

User can jump to any question using navigation. When user clicks navigation link, I changed my “currentQuestion” object to selected by user – object are pass by reference in JS, so if user modify something, I have results in my “central” array. And it’s ok.

I also use inputmask for masking inputs fields with very simple directive:

import Vue from 'vue'
import Inputmask from 'inputmask'

Vue.directive('mask', {
  bind (el, binding) {
    if (binding.value) {
      Inputmask(binding.value).mask(el)
    }
  }
})

And it’s also works fine… but not always. If user have a question with date mask, then jump to question with other mask and come back – date will not work. User must go to question without mask, then go back and it will work again.

After debugging, I know, that element is refreshed, but vue not bind correct data (from currentQuestion) to input:

methods: {
  getInputMask () {
    return this.currentQuestion.mask || null
  },

and usage:

<input type="text"
    :name="currentQuestion.identifier"
    v-mask="getInputMask()"
    v-model="currentQuestion.value"
    @keyup="afterModifyInput"
>

In result, I don’t know how can fix this issue

Answers:

You need to set an id for each element and use v-bind:key something like this:

<input type="text"
    v-bind:key="YOUR_ELEMENT.id"
    v-mask="getInputMask()"
    v-model="currentQuestion.value"
    @keyup="afterModifyInput"
>

I suppose this is your id

:name="currentQuestion.identifier"

Well, v-bind is used when you don’t know the exact content you’re going to render like a properties from request or JSON file.