4

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

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');
  }
}

那么此时如何在指令内部定义函数并在 and 内部使用bindcomponentUpdated

4

3 回答 3

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>

于 2019-03-14T08:21:29.273 回答
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)
 }
}
于 2019-03-14T08:17:01.873 回答
1

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

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 替换函数() => {}

于 2021-07-06T09:52:02.140 回答