Vue自定义私有指令

Vue自定义私有指令教程

Vue 除了支持自定义 全局指令 以外,还支持 Vue 自定义私有指令。

Vue自定义私有指令详解

语法

var vm = new Vue({ el :'#app', directives:{ 'func': { hook: function(el, binding) { } } } })

说明

Vue 自定义私有指令 我们需要在 Vue 的实例中,使用 directives 来定义,具体的参数和 Vue 全局指令一样。

案例

Vue自定义私有指令

<!DOCTYPE html> <html> <head> <title>Vue 自定义私有指令</title> <script type="text/javascript" src="./lib/vue-2.6.10.min.js"></script> </head> <style type="text/css"> </style> <body> <div id="app"> <h3 v-fontweight='200'>HaiCoder</h3> <h3 v-fontweight='800'>HaiCoder</h3> <p>嗨客网(www.haicoder.net)</p> </div> </body> <script type="text/javascript"> var vm = new Vue({ el :'#app', data:{ }, directives:{ 'fontweight': { bind: function(el, binding) { el.style.fontWeight = binding.value; } } } }) </script> </html>

浏览器运行效果如下图所示:

02 vue directive.png

我们使用了 Vue 自定义私有指令给两个 h3 都设置了相对应的样式。

Vue自定义私有指令总结

Vue 除了支持自定义全局指令以外,还支持 Vue 自定义私有指令。Vue 自定义私有指令语法:

var vm = new Vue({ el :'#app', directives:{ 'func': { hook: function(el, binding) { } } } })