1、分类
(1)私有自定义指令
(2)全局自定义指令
2、 私有自定义指令
(1)基本使用
-
在每个vue组建中,可以在directives节点下声明私有自定义指令
-
形参中el是绑定了此指令原生的DOM对象,是固定写法
-
v-是一个固定写法,自定义对象不需要写v-
-
当指令第一次被绑定到元素上的时候,会立即触发bind函数
<h1 v-color>App 根组件</h1> <script> export default { directives: { color: { bind(el) { el.style.color = "red"; }, }, }, }; </script>
(2)binding.value获取指令绑定的值
注意:不是一定叫binding,只是官方约定是binding
<h1 v-color="color">App 根组件</h1> <p v-color="'red'">测试</p> <script> export default { data() { return { color: "blue", }; }, directives: { color: { bind(el, binding) { el.style.color = binding.value; }, }, }, }; </script>
(3)update函数
每次DOM更新时被使用
directives: { color: { bind(el, binding) { el.style.color = binding.value; }, update(el, binding) { el.style.color = binding.value; } } }
(4)函数简写
bind和update函数中逻辑相同,则对象格式的自定义函数可以简写成函数格式:(color不是规定的,是需要什么写什么)
directives: { color(el, binding) { el.style.color = binding.value; } } }
3、全局自定义指令
-
全局共享的自定义指令需要通过进行声明
-
参数1:字符串,表示全局自定义指令的名字
-
参数2:对象,用来接收指令的参数值
-
全局声明的过滤器和指令在main.js中
-
方法2常用
-
全局自定义指令:Vue.directive('指令名字', function (el, binding) {})
-
过滤器:Vue.filter('过滤器名字',function(){})
//方法1 Vue.directive('color', { bind(el, binding) { el.style.color = binding.value }, update(el, binding) { el.style.color = binding.value }, }) //方法2 Vue.directive('color', function (el, binding) { el.style.color = binding.value })