Vue.js - 自定义指令详解1(生命周期函数、局部与全局指令、自定义v-focus指令)
作者:hangge | 2026-08-26 08:36
我们知道 Vue.js 内置了 v-show、v-for、v-model 等各种各样的指令。除了使用这些内置指令,Vue.js 也允许我们自定义指令。自定义指令分为以下两种。
- 自定义局部指令:在组件中通过 directives 选项定义,局部指令只能在当前组件中使用。
- 自定义全局指令:使用 app 的 directive 方法定义,全局指令可以在任意组件中使用。
下面我将通过样例演示如何自定义指令以及使用自定义指令。
一、基本用法
1,局部指令与全局指令
(1)下面样例定义一个 v-focus 的局部指令,该指令作用是当某个元素挂载完成后,可以自动获取焦点。
<template>
<div>
<input type="text" v-focus />
</div>
</template>
<script>
export default {
directives: { // 自定义局部指令 v-focus
focus: {
inserted(el, binding, vnode) {
console.log("focus mounted");
el.focus();
}
}
}
}
</script>
(2)如果需要定义全局指令,在 Vue 2 中可以使用 Vue.directive(指令名,配置对象)进行定义。

Vue.directive("focus", {
inserted(el, binding, vnode) {
console.log("focus mounted");
el.focus();
},
});
- 对于 Vue3,则可在 main.js 文件中,使用 App 实例自定义全局指令。
const app = createApp(App)
app.directive('focus', {
mounted(el) {
el.focus()
}
})
app.mount('#app')
2,自定义指令的生命周期函数
(1)下面代码演示的是 Vue.js 2 中自定义指令的生命周期函数。
<template>
<div class="my-component">
<button v-hangge v-if="counter < 2" @click="increment">当前计数: {{ counter }}</button>
</div>
</template>
<script>
export default {
name: 'MyComponent',
data() {
return {
counter: 0
}
},
directives: {
hangge: { // 自定义 v-hangge 局部指令
// 指令绑定时调用
bind() {
console.log("dereactive bind");
},
// 插入父节点时调用
inserted() {
console.log("dereactive inserted");
},
// 组件更新时调用
update() {
console.log("dereactive update");
},
// 更新完成后调用
componentUpdated() {
console.log("dereactive componentUpdated");
},
// 指令解绑时调用
unbind() {
console.log("dereactive unbind");
}
}
},
methods: {
increment() {
this.counter++;
}
}
}
</script>
- 可以看到到当页面加载时会调用 bind、inserted 生命周期函数。
- 当修改 counter 变量时,会触发指令 update、componentUpdated 生命周期函数的回调。
- 当 counter 大于等于 2,且 <button> 元素上的 v-if 为 false 时,会触发 unbind 生命周期函数的回调。

(2)下面代码演示的是 Vue.js 3 中自定义指令的生命周期函数。
<template>
<div>
<button v-hangge v-if="counter < 2" @click="increment">当前计数: {{ counter }}</button>
</div>
</template>
<script>
import { ref } from "vue";
export default {
directives: {
hangge: { //自定义 v-hangge 局部指令
// 在绑定元素的属性或事件监听器被应用之前调用
created() {
console.log("dereactive created");
},
// 当指令第一次绑定到元素并且在挂载父组件之前调用。
beforeMount() {
console.log("dereactive beforeMount");
},
// 在绑定元素的父组件被挂载后调用。
mounted() {
console.log("dereactive mounted");
},
// 在更新包含组件的VNode之前调用。
beforeUpdate() {
console.log("dereactive beforeUpdate");
},
// 在包含组件的VNode及其子组件的VNode更新后调用。
updated() {
console.log("dereactive updated");
},
// 在卸载绑定元素的父组件之前调用。
beforeUnmount() {
console.log("dereactive beforeUnmount");
},
// 当指令与元素解除绑定且父组件已卸载时,只调用一次。
unmounted() {
console.log("dereactive unmounted");
}
}
},
setup() {
const counter = ref(0);
const increment = () => counter.value++;
return { counter, increment }
}
}
</script>
- 可以看到到当页面加载时会调用 created、beforeMount、mounted 生命周期函数。
- 当修改 counter 变量时,会触发指令 beforeUpdate、updated 生命周期函数的回调。
- 当 counter 大于等于 2,且 <button> 元素上的 v-if 为 false 时,会触发 beforeUnmount、unmounted 生命周期函数的回调。
全部评论(0)