Vue指令的鈎子函數使用方法


在Vue 中可以把一系列復雜的操作包裝為一個指令。

什么是復雜的操作?

我的理解是:復雜邏輯功能的包裝、違背數據驅動的 DOM 操作以及對一些 Hack 手段的掩蓋等。我們總是期望以操作數據的形式來實現功能邏輯。

鈎子函數

對於自定義指令的定義,Vue2 有 5 個可選的鈎子函數。

bind: 只調用一次,指令第一次綁定到元素時調用,用這個鈎子函數可以定義一個在綁定時執行一次的初始化動作。
inserted: 被綁定元素插入父節點時調用(父節點存在即可調用,不必存在於 document 中)。
update: 被綁定元素所在的模板更新時調用,而不論綁定值是否變化。
componentUpdated: 被綁定元素所在模板完成一次更新周期時調用。
unbind: 只調用一次,指令與元素解綁時調用。

接下來,定義一個簡單的指令以驗證這些鈎子函數的觸發時機。

template

1
2
3
4
5
6
< div id = "app" >
  < my-comp v-if = "msg" :msg = "msg" ></ my-comp >
  < button @ click = "update" >更新</ button >
  < button @ click = "uninstall" >卸載</ button >
  < button @ click = "install" >安裝</ button >
</ div >

script

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
Vue.directive( 'hello' , {
  bind: function (el) {
   console.log( 'bind' )
  },
  inserted: function (el) {
   console.log( 'inserted' )
  },
  update: function (el) {
   console.log( 'update' )
  },
  componentUpdated: function (el) {
   console.log( 'componentUpdated' )
  },
  unbind: function (el) {
   console.log( 'unbind' )
  }
})
var myComp = {
  template: '<h1 v-hello>{{msg}}</h1>' ,
  props: {
   msg: String
  }
}
new Vue({
  el: '#app' ,
  data: {
   msg: 'Hello'
  },
  components: {
   myComp: myComp
  },
  methods: {
   update: function () {
    this .msg = 'Hi'
   },
   uninstall: function () {
    this .msg = ''
   },
   install: function () {
    this .msg = 'Hello'
   }
  }
})

頁面加載時

bind
inserted

組件更新時

點擊“更新”按鈕,更改數據觸發組件更新。

update
componentUpdated

卸載組件時

點擊“卸載”按鈕,數據置空否定判斷以觸發組件卸載。

unbind

重新安裝組件時

點擊“安裝”按鈕,數據賦值肯定判斷以觸發組件重新安裝。

bind
inserted

區別

從案例的運行中,對 5 個鈎子函數的觸發時機有了初步的認識。存疑的也就是bind和inserted、update和componentUpdated的區別了。

bind 和 inserted

據文檔所說,插入父節點時調用 inserted,來個測試。

1
2
3
4
5
6
7
8
bind: function (el) {
  console.log(el.parentNode) // null
  console.log( 'bind' )
},
inserted: function (el) {
  console.log(el.parentNode) // <div id="app">...</div>
  console.log( 'inserted' )
}

分別在兩個鈎子函數中輸出父節點:bind 時父節點為 null,inserted 時父節點存在。

update 和 componentUpdated

關於這兩個的介紹,從字眼上看感覺是組件更新周期有關,繼續驗證。

1
2
3
4
5
6
7
8
update: function (el) {
  console.log(el.innerHTML) // Hello
  console.log( 'update' )
},
componentUpdated: function (el) {
  console.log(el.innerHTML) // Hi
  console.log( 'componentUpdated' )
}

沒毛病,update 和 componentUpdated 就是組件更新前和更新后的區別。

結論

文檔說的沒錯……

 

轉自腳本之家...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM