vue自定义指令

1.什么是自定义指令
vue 官方提供了 v-text、v-for、v-model、v-if 等常用的指令。除此之外 vue 还允许开发者自定义指令。

2.自定义指令的分类
vue 中的自定义指令分为两类,分别是:
⚫ 私有自定义指令
⚫ 全局自定义指令

3.私有自定义指令
在每个 vue 组件中,可以在 directives 节点下声明私有自定义指令。示例代码如下:

  directives: {
    // 定义名为 color 的指令,指向一个配置对象
     color: {
      bind(el) {
        el.style.color = 'red'
      }
    } 
  }

4.使用自定义指令
在使用自定义指令时,需要加上 v- 前缀。示例代码如下:

<h1 v-color>App 根组件</h1>

5.为自定义指令动态绑定参数值
在 template 结构中使用自定义指令时,可以通过等号(=)的方式,为当前指令动态绑定参数值:

<h1 v-color="color">App 根组件</h1>

 data() {
    return {
      color: 'blue'
    }
  }

6.通过 binding 获取指令的参数值
在声明自定义指令时,可以通过形参中的第二个参数,来接收指令的参数值:

directives: {
    // 定义名为 color 的指令,指向一个配置对象
     color: {
      // 当指令第一次被绑定到元素上的时候,会立即触发 bind 函数
      // 形参中的 el 表示当前指令所绑定到的那个 DOM 对象
      bind(el, binding) {
        console.log('触发了 v-color 的 bind 函数')
        el.style.color = binding.value
      }
    }
  }

7.update 函数
bind 函数只调用 1 次:当指令第一次绑定到元素时调用,当 DOM 更新时 bind 函数不会被触发。 update 函数会在每次 DOM 更新时被调用。示例代码如下:

directives: {
    // 定义名为 color 的指令,指向一个配置对象
     color: {
      bind(el, binding) {
        console.log('触发了 v-color 的 bind 函数')
        el.style.color = binding.value
      },
      // 在 DOM 更新的时候,会触发 update 函数
      update(el, binding) {
        console.log('触发了 v-color 的 update 函数')
        el.style.color = binding.value
      }
    } 
   }

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

directives: {
 color(el, binding) {
      el.style.color = binding.value
  }
}

9.全局自定义指令
全局共享的自定义指令需要通过“Vue.directive()”进行声明,示例代码如下:

Vue.directive('color', function(el,binding){
	el.style.color = binding.value
})
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hobbies.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值