Vue.directive 自定義指令
阿新 • • 發佈:2019-01-08
一、什麼是全域性API?
全域性API並不在構造器裡,而是先宣告全域性變數或者直接在Vue上定義一些新功能,Vue內建了一些全域性API,比如我們今天要學習的指令Vue.directive。說的簡單些就是,在構造器外部用Vue提供給我們的API函式來定義新的功能。
二、Vue.directive自定義指令
我們在第一季就學習了內部指令,我們也可以定義一些屬於自己的指令,比如我們要定義一個v-jspang的指令,作用就是讓文字變成綠色。
在自定義指令前我們寫一個小功能,在頁面上有一個數字為10,數字的下面有一個按鈕,我們每點選一次按鈕後,數字加1.
三、自定義指令中傳遞的三個引數
el:
binding: 一個物件,包含指令的很多資訊。
vnode: Vue編譯生成的虛擬節點。
四、自定義指令的生命週期
自定義指令有五個生命週期(也叫鉤子函式),分別是 bind,inserted,update,componentUpdated,unbind
- bind:只調用一次,指令第一次繫結到元素時呼叫,用這個鉤子函式可以定義一個繫結時執行一次的初始化動作。
- inserted:被繫結元素插入父節點時呼叫(父節點存在即可呼叫,不必存在於document中)。
- update:被綁定於元素所在的模板更新時呼叫,而無論繫結值是否變化。通過比較更新前後的繫結值,可以忽略不必要的模板更新。
- componentUpdated:被繫結元素所在模板完成一次更新週期時呼叫。
- unbind:只調用一次,指令與元素解綁時呼叫。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script type="text/javascript" src="../assets/js/vue.js"></script> <title>vue.directive 自定義指令</title> </head> <body> <h1>vue.directive 自定義指令</h1> <hr> <div id="app"> <div v-jspang="color" id="aaa"> {{num}} </div> <p> <button @click='jia'>加分</button> </p> <p> <button onclick='unbind()'>解綁</button> </p> </div> <script type="text/javascript"> function unbind(){ app.$destroy(); } //自定義指令 Vue.directive('jspang',{ bind:function(el,binding,vnode){//被繫結 /** var s=JSON.stringify; el.innerHTML = 'name:' + s(binding.name) +'<br>' + 'value:' + s(binding.value) +'<br>' + 'expression:' + s(binding.expression) +'<br>' ; **/ el.style='color:'+binding.value; console.log('1 - bind'); }, inserted:function(){//繫結到節點 console.log('2 - inserted'); }, update:function(){//元件更新 console.log('3 - update'); }, componentUpdated:function(){//元件更新完成 console.log('4 - componentUpdated'); }, unbind:function(){//解綁 console.log('5 - unbind'); } }) var app=new Vue({ el:'#app', data:{ color:'green', num:10 }, methods:{ jia:function(){ this.num++; } } }) </script> </body> </html>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | bind:function(){//被繫結 console.log('1 - bind'); }, inserted:function(){//繫結到節點 console.log('2 - inserted'); }, update:function(){//元件更新 console.log('3 - update'); }, componentUpdated:function(){//元件更新完成 console.log('4 - componentUpdated'); }, unbind:function(){//解綁 console.log('1 - bind'); } |