wanderinghealer
wanderinghealer

Reputation: 71

Vuejs Local Directive Not Binding To Data When Passing A Method To Call

Defining a vuejs directive locally has issues when calling a method when being bound locally.

The problem: on tab/enter, look-up a value and set it based on what comes back (ie; setTimeout is the fake http call). Upon set time out completing, update the compute property.

I am aware of the migration docs says to use an 'eventHub' to communicate between the directive and the parent component. Is there another way to do this? If you check out the fiddle below, the global directive works perfectly while the local directive fails. I feel like the vm is not being bound properly on the local directive.

Local directive:

new Vue({
  el: '#vue',
  directive: {
    localSomething: {
      bind (el, b, n, o) {
        $(el).on('keydown', function(e) {
          if(e.keyCode == 13 || e.keyCode == 9) {
            b.value($(el).val());
          }
        });
      }    
    }
  },
  ...

Global directive:

Vue.directive('globalSomething', {
  bind (el, b, n, o) {
    $(el).on('keydown', function(e) {
      if(e.keyCode == 13 || e.keyCode == 9) {
        b.value($(el).val());
      }
    });
  }   
});

Html:

    Local: <input v-local-something="doSomething" />
    Global: <input v-global-something="doSomething" />

Method:

  methods: {
    doSomething: function(value) {
        let vm = this;
        setTimeout(function() {
          vm.item.name = value;
        });
    }

Fiddle here: https://jsfiddle.net/4g1xyy9h/

Upvotes: 1

Views: 1796

Answers (1)

Bert
Bert

Reputation: 82439

You have a typo. directive: should be directives:.

Updated fiddle.

Upvotes: 2

Related Questions