组件负责结构和业务交互,组合式函数负责复用响应式逻辑,但有些功能直接作用于具体 DOM 节点,例如自动聚焦、监听元素事件、设置原生属性。Vue 3 自定义指令适合封装这类底层行为。本文以后台编辑界面为例,讨论指令注册、生命周期、更新、事件清理与服务端渲染边界。
下列代码块按各节独立展示,实际接入时应结合相应的样式、脚本或组件文件。
1. 在模板中表达自动聚焦意图
如果每个编辑组件都在 mounted 阶段重复查询自己的输入框,就会增加 DOM 耦合。自动聚焦可以注册为局部指令,但应只在用户预期的编辑场景使用,避免页面加载时抢走焦点。以下模板属于 Vue 单文件组件,不应当作为普通 HTML 直接执行。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/9968e81dcb63c3d5b02eeafcc6bb7543f8892c68">
<template><label>项目名称<input v-focus name="projectName" required></label></template>
</div>
<script setup>
const vFocus = {
mounted(el) { el.focus(); }
};
</script>
<template><label>项目名称<input v-focus name="projectName" required /></label></template>
2. 使用 binding.value 控制指令开关
指令值适合表达明确的启用条件。动态更新时应比较新旧值,仅在条件由 false 变为 true 时聚焦,避免父组件任意重新渲染都导致光标跳回输入框。disabled 元素不应执行自动聚焦。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/a0b72e92a66a0430564de512a3a06595008bf2cf">
<template><input v-focus="editing" :disabled="!editing" aria-label="编辑名称"></template>
</div>
export const vFocus = {
mounted(el, binding) {
if (binding.value && !el.disabled) el.focus(); },
updated(el, binding) {
if (binding.value && !binding.oldValue && !el.disabled) el.focus(); }
};
3. 通过 arg 表达行为差异
指令参数适合数量较少且语义稳定的配置。以下指令用于给元素设置可访问的文本标签,参数值限定在显式支持的属性中,避免任意属性写入。一般情况下模板原生绑定更简单,此处主要展示指令参数处理。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/6b704478e0db7d11659844d36dd864f443885ef2">
<template><button v-label:description="helpId" type="button">执行任务</button></template>
</div>
function updateLabel(el, binding) {
const attr = binding.arg === 'description' ? 'aria-describedby' : 'aria-label';
if (typeof binding.value === 'string' && binding.value.trim()) el.setAttribute(attr, binding.value);
else el.removeAttribute(attr);
}
export const vLabel = {
mounted: updateLabel, updated: updateLabel };
// 此示例使用静态参数;动态参数需要单独记录旧属性并清理。
4. 用 WeakMap 保存每个元素的监听器
同一个指令可能绑定到多个节点。把所有回调存放在单个模块变量中会导致组件之间覆盖。使用 WeakMap 按元素维护独立记录,并在卸载时主动移除监听器。WeakMap 不会代替事件监听器清理。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/14c614a55eeb393861f2bd9f11ed2e369dc47b43">
<template><section v-escape="closeEditor" tabindex="0" aria-label="编辑区域"><input aria-label="名称"></section></template>
</div>
const escapeHandlers = new WeakMap();
export const vEscape = {
mounted(el, binding) {
const state = {
callback: binding.value, listener: null };
state.listener = event => {
if (event.key === 'Escape' && typeof state.callback === 'function') state.callback(event); };
escapeHandlers.set(el, state);
el.addEventListener('keydown', state.listener);
},
updated(el, binding) {
const state = escapeHandlers.get(el); if (state) state.callback = binding.value; },
unmounted(el) {
const state = escapeHandlers.get(el); if (state) el.removeEventListener('keydown', state.listener); escapeHandlers.delete(el); }
};
5. 监听全局事件时明确范围
点击区域外部关闭是典型的 DOM 行为,但全局监听必须在卸载时释放。利用 composedPath 判断事件是否来自区域内部,同时让绑定函数自行判断业务是否允许关闭。使用捕获阶段时必须在移除时传入匹配的 capture 参数。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/0d0986a75b9221d2886d09123922ea7659736438">
<template><section v-outside="closeMenu" class="menu-panel"><button type="button">选择项目</button><ul><li>当前项目</li></ul></section></template>
</div>
const outsideStates = new WeakMap();
export const vOutside = {
mounted(el, binding) {
const state = {
callback: binding.value, listener: null };
state.listener = event => {
if (!event.composedPath().includes(el) && typeof state.callback === 'function') state.callback(event); };
outsideStates.set(el, state); document.addEventListener('pointerdown', state.listener, true);
},
updated(el, binding) {
const state = outsideStates.get(el); if (state) state.callback = binding.value; },
unmounted(el) {
const state = outsideStates.get(el); if (state) document.removeEventListener('pointerdown', state.listener, true); outsideStates.delete(el); }
};
6. 不要用指令替代框架模板渲染
指令直接删除由 Vue 管理的元素,或修改其 children 结构,可能让虚拟 DOM 与实际 DOM 不一致。需要展示或隐藏整块内容时,优先使用 v-if、v-show 或组件,而不是开发一个自行删除节点的自定义指令。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/35cd1547a7cf0e7e54d4c946272cfaec75538f9a">
<template><section v-if="editing" class="editor-panel"><h2>编辑项目</h2><input aria-label="项目名称"></section></template>
</div>
7. 在指令中处理原生滚动行为
需要在新出现的错误区域定位用户时,可以为单个元素定义滚动指令。这里仅在条件由关闭变为开启时执行,采用 nearest 避免不必要的整体页面跳动,并让 CSS 管理滚动动画偏好。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/3771b3b79e40ed7d709371ccd07c25a551db2db8">
<template><p v-reveal="hasError" role="alert">请检查必填字段。</p></template>
</div>
function reveal(el, binding) {
if (binding.value) el.scrollIntoView({
block: 'nearest', behavior: 'auto' }); }
export const vReveal = {
mounted: reveal, updated(el, binding) {
if (!binding.oldValue && binding.value) reveal(el, binding); } };
8. 在应用入口注册通用行为
只有跨多个组件稳定复用的指令才适合全局注册。局部指令则通过组件自己的 setup 变量或 directives 选项管理,避免每个功能模块都占用全局名称。下方代码假设 focus.js 和 escape.js 已分别导出对应指令。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/f200d8339bffbdc1bbf2701d37d5331d490f24ab">
<template><section v-escape="cancel" tabindex="0"><input v-focus="editing" aria-label="编辑标题"></section></template>
</div>
import {
createApp } from 'vue';
import App from './App.vue';
import {
vFocus } from './focus.js';
import {
vEscape } from './escape.js';
const app = createApp(App);
app.directive('focus', vFocus);
app.directive('escape', vEscape);
app.mount('#app');
9. 区分 SSR 输出与客户端行为
服务端不能调用 document.addEventListener 或 el.focus。DOM 行为应留在 mounted 等客户端生命周期。如果某个指令确实需要为服务端 HTML 输出属性,可以通过 getSSRProps 返回纯属性对象,但不应依赖浏览器全局对象。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/2e6f65d0dd4013766bbf6058b7f840329f3ffb02">
<template><article v-status="status"><h2>任务进度</h2><p>{
{ status }}</p></article></template>
</div>
function statusProps(value) {
return {
'data-status': String(value ?? '') }; }
function applyStatus(el, binding) {
el.setAttribute('data-status', statusProps(binding.value)['data-status']); }
export const vStatus = {
mounted: applyStatus, updated: applyStatus, getSSRProps(binding) {
return statusProps(binding.value); } };
10. 测试重新挂载与参数变化
验证指令时应覆盖多个元素同时挂载、绑定回调变化、元素卸载后全局事件,以及键盘操作。尤其是弹层外部点击需要考虑 Teleport 后 DOM 位置、Shadow DOM 事件路径与实际的交互边界。指令并不自动提供完整弹层无障碍支持。
<div id="https://github.com/tiktokwuyu-ux/technical-notes/commit/a5d37d9a44d7b56c061d41212d31f619d55f8f63">
<section class="directive-test"><h2>编辑区域验证</h2><ul><li>重新打开后监听器只注册一次</li><li>关闭后全局事件不再触发</li><li>更新回调后使用当前行为</li></ul></section>
</div>
总结
自定义指令适用于稳定、直接关联 DOM 的行为复用。应限制它管理的节点和属性,保证 mounted、updated、unmounted 的职责清晰,并在 SSR 和重新挂载场景中保持生命周期对称。复杂业务状态仍应交由组件与组合式函数组织。