9

I've created a vue directive that I'm attaching to multiple input elements on the same page, and have noticed that when I start typing in one of them, the 'update' event fires for all elements in the page. I had expected to only have one event, for the particular element that I had updated.

My question is, Is there a way to prevent the event firing, or filtering the events so that I can handle only the input that is changing?

Heres the code for my directive and view:

Vue.directive('test', {
  bind: (el) => {
    console.log(el.id + " bound")
  },
  update: (el) => {
    console.log(el.id + " updated")
  }
})

new Vue({
  el: "#app",
  data: {
    testval1: null,
    testval2: null,
  },
  methods: {
  }
})

and the template:

<div id="app">
  <input id="testinput1" v-model="testval1" v-test />
  <input id="testinput2" v-model="testval2" v-test />
</div>

Here is a JSFiddle of the issue: https://jsfiddle.net/eywraw8t/415288/

In this JSFiddle, you can see in the console that if you type into the input field, it fires the update for both input fields.

Matt M
  • 179
  • 1
  • 7

2 Answers2

1

I think the best way is to use bind. Your directive there will be a directive that works on every element with v-test directive specified. Here is simple approach to solve your issue

Vue.directive('test', {


  bind: (el) => {
    console.log(el.id + " bound")
    const handler = (e) => {
        console.log('e', e.target)
      if (el == e.target) {
        console.log(el.id + " firing")
      }
    }
    el.vueTest = handler
    // add Event Listeners
    document.addEventListener('input', handler)
  },
  unbind (el, binding) {
    // Remove Event Listeners
    document.removeEventListener('input', el.vueTest);
    el.vueTest = null;
  }
})

Hope this will help you :)

0

You may store the element on bind and check for it on the update like this:

Vue.directive('test', (() => {
  let element;
  return {
    bind(el) {
      element = el;
      console.log(el.id + " bound");
    },
    update(el) {
      if (element === el) {
        console.log(el.id + " updated");
      }
    },
  };
})());
Hafez Divandari
  • 8,381
  • 4
  • 46
  • 63