Vue自定义指令
封面图
•
2025-11-19
•
Vue
0
0
0
0
在 Vue 中,**自定义指令(Custom Directives)** 是一种非常强大的功能,允许你直接操作 DOM。Vue 提供了 `v-` 前缀的指令,比如 `v-if`、`v-show`、`v-for` 等,但有时候你需要对 DOM 进行更底层的操作,这时候就可以使用自定义指令。 --- ## ✅ 一、什么是自定义指令? 自定义指令是通过 `Vue.directive` 注册的,用于在模板中以 `v-xxx` 的形式使用,例如 `v-focus`、`v-color` 等。 --- ## ✅ 二、自定义指令的生命周期钩子 Vue 指令有以下几个 **钩子函数**(hook functions),它们会在不同阶段被调用: | 钩子函数 | 调用时机 | |----------|----------| | `bind` | 指令第一次绑定到元素时调用(仅一次) | | `inserted` | 元素插入父节点时调用(如:DOM 已挂载) | | `update` | 所有组件数据更新后调用(包括子组件) | | `componentUpdated` | 组件和子组件都更新完毕后调用 | | `unbind` | 指令从元素上解绑时调用 | --- ## ✅ 三、自定义指令的语法(Vue 2 vs Vue 3) ### 📌 Vue 2 的写法: ```js // main.js 或某个插件中注册 Vue.directive('focus', { // 指令的定义对象 inserted: function (el) { el.focus() } }) ``` ### 📌 Vue 3 的写法(使用 `app.directive()`): ```js const app = createApp(App) app.directive('focus', { mounted(el) { el.focus() } }) ``` > 注意:Vue 3 中不再支持 `Vue.directive()`,而是使用 `app.directive()`。 --- ## ✅ 四、自定义指令示例 ### 示例 1:自动聚焦指令 `v-focus` ```js // Vue 3 app.directive('focus', { mounted(el) { el.focus() } }) ``` ```vue <template> <input v-focus placeholder="自动聚焦"> </template> ``` --- ### 示例 2:高亮文本指令 `v-highlight` ```js // Vue 3 app.directive('highlight', { mounted(el, binding) { el.style.backgroundColor = binding.value || 'yellow' }, updated(el, binding) { el.style.backgroundColor = binding.value || 'yellow' } }) ``` ```vue <template> <div v-highlight="'lightblue'">这段文字会高亮显示</div> </template> ``` --- ### 示例 3:点击外部关闭指令 `v-click-outside` ```js // Vue 3 app.directive('click-outside', { mounted(el, binding) { const handler = (e) => { if (!el.contains(e.target)) { binding.value(e) } } el._handler = handler document.addEventListener('click', handler) }, unmounted(el) { document.removeEventListener('click', el._handler) } }) ``` ```vue <template> <div v-click-outside="handleClickOutside"> 点击外部区域会触发事件 </div> </template> <script> export default { methods: { handleClickOutside() { alert('点击了外部区域!') } } } </script> ``` --- ## ✅ 五、传递参数给指令 你可以通过 `binding.value` 获取传入的值,也可以使用 `binding.arg` 获取修饰符或参数。 ```js // 指令使用 <div v-my-directive:color="someColor"></div> ``` ```js app.directive('my-directive', { mounted(el, binding) { console.log(binding.arg) // 输出 "color" console.log(binding.value) // 输出 someColor 的值 } }) ``` --- ## ✅ 六、使用 `v-model` 的自定义指令(Vue 2) Vue 2 中可以结合 `v-model` 使用自定义指令,但 Vue 3 不再支持这种方式,因为 `v-model` 是一个语法糖,内部使用 `modelValue` 和 `update:modelValue`。 --- ## ✅ 七、总结 | 功能 | 说明 | |------|------| | 自定义指令 | 通过 `Vue.directive()` 或 `app.directive()` 注册 | | 生命周期钩子 | `bind`, `inserted`, `update`, `componentUpdated`, `unbind` | | 参数传递 | 通过 `binding.value`、`binding.arg`、`binding.modifiers` | | 适用场景 | 操作 DOM、监听事件、封装通用行为等 | --- 如果你有具体需求(比如实现一个拖拽指令、懒加载图片、复制到剪贴板等),我可以帮你写出对应的自定义指令代码 😊
上一篇:
Vue组件透传 Attributes
下一篇:
Vue插件
标题录入,一次不能超过6条
留言
评论