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!" })