1 //vue中自定義指令 2 //使用 Vue.directive(id, [definition]) 定義全局的指令 3 //參數1:指令的名稱.注意,在定義的時候,指令的名稱前面,不須要加 v-前綴; 可是, 在調用的時候,必須在置頂的名稱前加上 v-前綴來進行調用 4 //參數2: 是一個對象, 這個對象身上,有一些指令相關的函數,這些函數能夠在特定的階段,執行相關的操做。 5 6 Vue.directive("focus", { 7 // 注意: 在每一個函數中, 第一個參數永遠是el, 表示被綁定了指令的那個元素,這個el參數,是一個原生的JS對象 8 bind: function(el){ // 每當指令綁定到元素上的時候,會當即執行這個bind函數,【觸發一次】 9 // 10 }, 11 inserted: function(el){ // inserted 表示元素插入到DOM中的時候,會執行inserted函數【觸發一次】 12 el.focus() 13 }, 14 updated: function(el) { // 當VNode更新的時候,會執行updated,可能【會觸發屢次】 15 // 16 } 17 }) 18 19 20 //調用: 21 //注意: Vue中全部的指令,在調用的時候,都以 v- 開頭 22 <input type="text" class="form-control" v-model="keywords" v-focus/>
若是指令須要多個值,能夠傳入一個JS對象字面量,指令函數可以接受全部合法類型的JS表達式。vue
<div v-demo="{ color: 'white', text: 'hello!' }"></div>
Vue.directive('demo', function (el, binding) { console.log(binding.value.color) // => "white" console.log(binding.value.text) // => "hello!" })