Vue自定义指令详解(2)

//注册一个全局自定义指令v-focus // 当绑定元素插入到DOM中 // 聚焦元素 <div> <input v-focus> /div> Vue.directive('focus', { inserted: function (el) { el.focus() } }); var app = new Vue({ el: '#app' });

下面将讲解一个使用钩子函数参数的例子,将元素的字体色设置为 #fff,将背景色设置为传入指令的参数 red,并将指令名指令绑定值,指令绑定值的表达式,传入指令的参数显示在中。

代码如下:

<div v-demo-directive:red="message"></div> <script> Vue.directive('demoDirective', { bind: function(el, binding, vnode){ el.style.color = '#fff' el.style.backgroundColor = binding.arg el.innerHTML = '指令名 name:' + binding.name + '<br>' + '指令绑定值 value:' + binding.value + '<br>' + '指令绑定表达式expression:' + binding.expression + '<br>' + '传入指令的参数argument - ' + binding.arg + '<br>' }, }); var demo = new Vue({ el: '#example', data: { message: 'hello!' } }) </script>

3. 对象字面量

+ 如果指令需要多个值,则可以传入一个 javascript 对象字面量
+ 指令可以使用任意合法的 javascript 表达式

<div v-demo-directive="{ color: 'white', text: 'hello!' }"></div> Vue.directive('demoDirective', function(el, binding, vnode){ console.log(binding.value.color); console.log(binding.value.text); }); var demo = new Vue({ el: '#app' })

4. 字面指令

+ 当指令使用了字面修饰符时,它的值将按普通字符串处理并传递给 update 方法
+ update 方法将只调用一次,因为普通字符串不能影响数据变化
+ 若在创建自定义指令时,设置 inListerral: true 则特性值将被视作字符串,并将赋值给该指令的expression,字面指令不会建立数据监视。

div v-myEx.literal = 'foo bar baz'></div> Vue.directive('myEx',function(el, binding, vnode){ console.log(binding.value.literal) }) var hah = new Vue({ el: '#isExample' })

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyjwxz.html