Vue自定义指令

1. 什么是自定义事件

vue 官方提供了 v-text,v-for,v-model,v-if 等常用指令。除此之外 vue 还允许开发者自定义指令。

2. 自定义指令的分类

  • 私有自定义指令
  • 全局自定义指令

3. 私有自定义指令

3.1 基本使用

在每个 vue 组件中,可以在 directives 节点下声明私有自定义指令

// 私有自定义指令放在 deactivated 节点下
directives:{
    // 定义 color 自定义指令 
    // 后面写配置对象
    color:{
        // 当 color 指令刚绑定到元素身上时
        // 就会自动立即触发 bind 函数
        bind(el){
            // 形参中的 el 表示当前指令所绑定的 DOM 对象
            el.style.color = 'red'
        }
    }
}

3.2 binding.value

通过 binding.value 获取指令绑定值

<h1 v-color="color"> App.vue 根组件</h1>
<h2 v-color="'green'">测试</h2>
directives:{
    color:{
        bind(el,binding){
            // 形参中的 el 表示当前指令所绑定的 DOM 对象
            el.style.color = binding.value
        }
    }
}

3.3 update 函数

  • bind 函数只调用一次:当指令第一次绑定到元素时调用
  • update 函数会在每次 DOM 更新时被调用
  • update 函数在指令绑定的时候不会被调用!
directives:{
    color:{
        bind(el,binding){
            // 形参中的 el 表示当前指令所绑定的 DOM 对象
            console.log('bind')
            el.style.color = binding.value
        },
        update(el,binding){
            console.log('update')
            el.style.color = binding.value
        }
    }
}

3.4 函数简写

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

directives:{
    color(el,binding){
        console.log('color简写')
        el.style.color = binding.value
    }
}

4. 全局自定义指令

通过 Vue.directive()方法在 main.js 中定义全局自定义指令

// 全局自定义指令
Vue.directive('color' , {
  bind(el,binding){
    console.log('color简写')
    el.style.color = binding.value
  },
  update(el,binding){
    console.log('color简写')
    el.style.color = binding.value
  }
})
//简写形式:
Vue.directive('color' ,function(el,binding){
  console.log('color简写')
  el.style.color = binding.value
})

5. main.js 中的小提示

Vue.config.productionTip = true

在终端会有如下提示:

You are running Vue in development mode.vue.runtime.esm.js?c320:8484

您正在开发模式中运行Vue

Make sure to turn on production mode when deploying for production. See more tips at https://vuejs.org/guide/deployment.html

在为生产部署时,请确保打开生产模式。

请参阅 …

  • 5
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值