如何在Vue指令中定义方法?

时间:2019-03-14 07:36:01

标签: javascript vue.js vuejs2 vue-component vue-directives

我有指令,我想在指令内创建一个本地方法,并在hook函数中使用它。这是我的代码:

export const OutsideClick = {
  bind (el, binding, vnode) {
    console.log(new Vue());
    // call method1()
  },
  componentUpdated(el, binding, vnode) {
    console.log('updated comp', binding);
    if(binding.value[1]()) {
      // call method1();
    }
  },
  unbind(el, binding, vnode) { 
    console.log('unbinding');
  }
}

因此,此时如何在指令中定义函数并在bindcomponentUpdated中使用它?

3 个答案:

答案 0 :(得分:2)

我认为您不能在指令本身内添加方法。但是您可以在指令外部声明该方法,然后在指令内部调用它。

function method1 (el, binding, vnode) {
 ...
}

export const OutsideClick = {
 bind (el, binding, vnode) {
  console.log(new Vue());
  method1(el, binding, vnode)
 },
 componentUpdated(el, binding, vnode) 
 {
  console.log('updated comp', binding);
  if(binding.value[1]()) {
   method1(el, binding, vnode)
  }
 },
 unbind(el, binding, vnode) { 
  console.log('unbinding')
  method1(el, binding, vnode)
 }
}

答案 1 :(得分:2)

好吧,您需要按照以下示例在指令之外添加函数并在生命周期方法内调用它。

Vue.directive("color", {

  "bind": function() {
    console.log("directive active");
    hello();
  },


  "unbind": function() {
    console.log("directive deactive");
  },


  "update": function(newValue, oldValue) {
    var el = $(this.el); 


    if (this.arg == 'background')
      el.css('background', newValue);
    else
      el.css('color', newValue);
  },
});

function hello() {
  console.log('hello');
}

new Vue({
  el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.24/vue.min.js"></script>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>

<div id="app">
  <h2>Color</h2>
  <select v-model="color">
    <option value="#f00">Red</option>
    <option value="#0f0">Green</option>
    <option value="#00f">Blue</option>
    <option value="#000" selected>Black</option>
  </select>
  <br><br>
  <div v-color="color">
    Hello world!!!
  </div>
  <h2>Background</h2>
  <select v-model="color2">
    <option value="#f00">Red</option>
    <option value="#0f0">Green</option>
    <option value="#00f">Blue</option>
    <option value="#000" selected>Black</option>
  </select>
  <br><br>
  <div v-color:background="color2">
    Hello world!!!
  </div>

</div>

答案 2 :(得分:0)

也许有人会发现它有帮助。诀窍是用构造函数包装指令。

function myDirective() {
  this.myMethod = function() {
    console.log('My method')
  }
  return {
    bind: function(el) {
      el.addEventListener('click', this.myMethod)
    }.bind(this),
    update: function() {
      this.myMethod()
    }.bind(this),
    unbind: function(el) {
      el.removeEventListener('click', this.method)
    }.bind()
  }
}

Vue.directive('myDirective', new myDirective())
new Vue({
  el: '#app'
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <button v-my-directive>Just a button</button>
</div>

带有 .bind(this) 的函数也可以替换为 lambdas () => {}