Vue自定义指令详解

2020-06-14 06:04:31易采站长站整理

代码如下:


<div id="example" 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 id="app" 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 id="isExample" 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'
})