ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

Vue2和Vue3自定义指令的写法

2026/8/18 6:05:28 拓冰建站 浏览量
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()}
}