指令鉤子函數會被傳入以下參數:
具體事例
clickoutside.js
用途:clickoutside.js主要用于解決點解元素外的地方時執行函數 主要應用的常見有彈出層點擊遮罩層是隱藏窗口,或者一些彈出層點擊其他地方要消失的場景
v-clickoutside具體是怎么實現的
答:主要是通過在bind中定義函數 通過判斷是否包含元素,執行binding.value函數
export default { /*  @param el 指令所綁定的元素  @param binding {Object}   @param vnode vue編譯生成的虛擬節點  */ bind (el, binding, vnode) {  const documentHandler = function(e) {     if(!vnode.context || el.contains(e.target)) {    return false;   }   if (binding.expression) {    binding.value(e)   }  }    document.addEventListener('click', documentHandler) }, update (el, binding) {  }, unbind(el) {  document.removeEventListener('click', documentHandler); }}Vue.directive使用注意
首先,Vue.directive要在實例初始化之前,不然會報錯,還有,定義的指令不支持駝峰式寫法,也會報下面同樣的錯,雖然在源碼中沒有找到在哪里統一處理大小寫,但是在有關directive的方法中捕捉到的指令命名統一變為小寫,所以,還是用'-'或者'_'分割吧。
vue.js:491 [Vue warn]: Failed to resolve directive: xxx
然后,其定義方式有兩種,一種是Vue.directive('xxx', function(el, bind, vNode){}),其中el為dom,vNode為vue的虛擬dom,bind為一較復雜對象,詳情可見Vue-directive鉤子函數中的參數的參數,還有一種,為
Vue.directive('my-directive', { bind: function () {}, inserted: function () {}, update: function () {}, componentUpdated: function () {}, unbind: function () {}})參數代表的含義,參見鉤子函數描述
最后,要使用自定義的指令,只需在對用的元素中,加上'v-'的前綴形成類似于內部指令'v-if','v-text'的形式。
// Vue.directive      Vue.directive('test_directive', function(el, bind, vNode){        el.style.color = bind.value;      });      var app = new Vue({        el: '#app',        data: {          num: 10,          color: 'red'        },        methods: {          add: function(){            this.num++;          }        }      });當然,也可以將method中的方法加入,bind.value即為methods中的方法。
<div id="app">      <div v-test_directive="changeColor">{{num}}</div>      <button @click="add">增加</button>    </div>    <script type="text/javascript">      // Vue.directive      Vue.directive('test_directive', function(el, bind, vNode){        el.style.color = bind.value();      });      var app = new Vue({        el: '#app',        data: {          num: 10,          color: 'red'        },        methods: {          add: function(){            this.num++;          },          changeColor: function(){            return this.color;          }        }      });這種形式,可以模仿'v-once',并進行一定的復雜邏輯,但是想要完全達到'v-once',可能需要考慮Vue-directive的鉤子函數各個周期。下面是固定num的值,使得add的方法無效。
<div id="app">      <div v-test_directive="changeColor">{{num}}</div>      <button @click="add">增加</button>    </div>    <script type="text/javascript">      // Vue.directive      Vue.directive('test_directive', function(el, bind, vNode){        el.style.color = bind.value();      });      var app = new Vue({        el: '#app',        data: {          num: 10,          color: 'red'        },        methods: {          add: function(){            this.num++;          },          changeColor: function(){            this.num = 20;            return this.color;          }        }      });因為小生剛剛接觸vue,所以,希望前輩能多加指點。也希望大家多多支持武林網。
新聞熱點
疑難解答