Vue2和Vue3自定义指令的写法

目录

Vue2

Vue3


Vue2

全局指令

//全局指令
Vue.directive('自定义指令名',{
inserted(el,binding){
执行逻辑
    },
 updated(el,binding){
执行逻辑
 }
})

局部指令


//局部指令
directives:{
    自定义指令名:{
        inserted(el){
            执行逻辑
        }
    }
    
    

 例如:

全局指令

Vue.directive( ' bgcolor' , {
	inserted (el, binding) {
	console.log(el, binding)
	el.style.backgroundColor = binding.value
},
    //实时更新
update (el, binding){
	el.style. backgroundColor = binding.value
	}
})

局部指令

//指令
directives:{
    //指令所在的dom元素插入到dom树中执行这个函数
//focus(el){ //el指令所在的dom
//    //el就是指令所在元素即文本框
  //  el.focus()
	
//	}
    
    //相当于
    focus:{
		inserted(el){
       el.focus()
		}
    }
}

Vue3

全局指令

//指令
directives:{
    //指令所在的dom元素插入到dom树中执行这个函数
//focus(el){ //el指令所在的dom
//    //el就是指令所在元素即文本框
  //  el.focus()
    
//    }
    
    //相当于
    focus:{
        inserted(el){
       el.focus()
        }
    }
}

局部指令

//局部指令
const 自定义指令名={
    mounted(el){
       执行逻辑
    }

例如

全局指令

import { createApp } from 'vue'
import App from './App.vue'

import CustormComp from './components/CustormComp.vue'
const app=createApp(App)

// 注册全局指令
app.directive('color',{
    mounted(el,binding){
        el.style.backgroundColor=binding.value
    },
    updated(el,binding){
        el.style.backgroundColor=binding.value
    }
})


//  钩子函数只用到mounted和updated可以简写为下面的函数
// 假如需要用到其他钩子函数或mounted和updated执行不同逻辑要写成对象

app.directive('color',(el,binding)=>{
    el.style.backgroundColor=binding.value
})

 局部指令

//局部指令
const vFocus={
    mounted(el){
        el.focus()
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值