9. Vue自定义指令

目录

一、私有自定义指令

二、全局自定义指令


一、私有自定义指令

私有自定义指令:指的是定义在组件内部的自定义指令,只能在本组件内使用,其他组件无法使用

语法:

自定义指令,定义在 directives 节点下。其中 el 指向 被绑定的 原生DOM 对象

binding 参数用来接收用户传递过来的值

看下面代码:

定义了一个自定义指令:v-color

<template>

    <p v-color="color">你好vue</p>

</template>

<script>

export default {

    data() {

        return {

            color: "red"

        }

    },

    directives: {

        color: {

//  el 指向 被绑定 的 原生DOM 对象

//  binding 参数用来接收用户传递过来的值

            bind(el, binding) {

                el.style.color = binding.value

            }

        }

    }

}

</script>

注意:bind() 函数,只有在第一次被绑定的时候会执行!这时候需要用到 update()函数来监听当DOM元素发生改变的时候执行

update() 函数 , 在DOM元素的属性值发生改变的时候会被触发

directives: {

    color: {

        bind(el, binding) {

            el.style.color = binding.value

        },

        upadte(el, binding) {

            el.style.color = binding.value

        }

    }

}

bind() 和 update() 函数可以简写:

前提:如果bind和 update 函数中的逻辑完全相同,则对象格式的自定义指令可以简写成函数格式

directives: {

    color(el, binding) {

        el.style.color = binding.value

    }

}


二、全局自定义指令

 全局共享的自定义指令需要通过 'Vue.directive()'  进行声明,写在main.js文件中,示例代码如下:

// 全局自定义指令,color是自定义指令的名字

/* Vue.directive('color', {

    bind(el, binding) {

        el.style.color = binding.value

    },

    update(el, binding) {

        el.style.color = binding.value

    },

}) */

下面是简写,前提是bind 和 update 函数中逻辑完全相同才可以:

Vue.directive('color', function(el, binding) {

    el.style.color = binding.value

})

猜你喜欢

转载自blog.csdn.net/Mr_LiuP/article/details/123355982