在 Vue 3 中,app.directive 是一個全局 API,用于注冊或獲取全局自定義指令。以下是關于 app.directive 的詳細說明和使用方法
app.directive 用于定義全局指令,這些指令可以用于直接操作 DOM 元素。自定義指令在 Vue 3 中非常強大,可以用來封裝復雜的 DOM 操作、復用常見的交互行為
1.定義全局指令
app.directive('highlight', {created(el, binding, vnode) {// 在元素的屬性或事件監聽器應用前調用},beforeMount(el, binding, vnode) {// 在元素插入到 DOM 前調用el.style.backgroundColor = binding.value || 'yellow';},mounted(el, binding, vnode) {// 在元素插入到 DOM 后調用},beforeUpdate(el, binding, vnode, prevVnode) {// 在元素更新前調用},updated(el, binding, vnode, prevVnode) {// 在元素更新后調用},beforeUnmount(el, binding, vnode) {// 在元素卸載前調用},unmounted(el, binding, vnode) {// 在元素卸載后調用}
});
鉤子參數?
指令的鉤子會傳遞以下幾種參數:
el:指令綁定到的元素。這可以用于直接操作 DOM。binding:一個對象,包含以下屬性。value:傳遞給指令的值。例如在 v-my-directive="1 + 1" 中,值是 2。
oldValue:之前的值,僅在 beforeUpdate 和 updated 中可用。無論值是否更改,它都可用。
arg:傳遞給指令的參數 (如果有的話)。例如在 v-my-directive:foo 中,參數是 "foo"。
modifiers:一個包含修飾符的對象 (如果有的話)。例如在 v-my-directive.foo.bar 中,修飾符對象是 { foo: true, bar: true }。
instance:使用該指令的組件實例。
dir:指令的定義對象。
vnode:代表綁定元素的底層 VNode。prevVnode:代表之前的渲染中指令所綁定元素的 VNode。僅在 beforeUpdate 和 updated 鉤子中可用。
舉例來說,像下面這樣使用指令:
<div v-example:foo.bar="baz">
2.使用指令在組件中使用自定義指令時,只需在模板中綁定指令即可:
<template><p v-highlight="'aqua'">This paragraph will be aqua-colored.</p>
</template>
3.Vue3的自定義指令提供了以下生命周期鉤子:
- created:在元素的屬性或事件監聽器應用前調用。
- beforeMount:在元素插入到 DOM 前調用。
- mounted:在元素插入到 DOM 后調用。
- beforeUpdate:在元素更新前調用。
- updated:在元素更新后調用。
- beforeUnmount:在元素卸載前調用。
- unmounted:在元素卸載后調用。
自定義指令
- v-copy
directive/copy/index.tsimport type { Directive, DirectiveBinding, App } from 'vue'
import { ElMessage } from 'element-plus'
import {EventType} from '../types'function addEventListener(el: Element, binding: DirectiveBinding) {const { value, arg,modifiers } = bindingconsole.log(value,modifiers,arg,'ssss');// 確定事件類型和提示消息const eventType: EventType = modifiers.dblclick ? 'dblclick' : 'click'const message = arg || '復制成功' as stringel.setAttribute('copyValue', String(value))const copyHandler = async ():Promise<void> => {try {if (navigator.clipboard) {await navigator.clipboard.writeText(el.getAttribute('copyValue') || '')} else {legacyCopy(el.getAttribute('copyValue') || '')}// 非靜默模式顯示提示if (!modifiers.quiet) {ElMessage({message: message,type: 'success',})} } catch (err) {ElMessage.error('復制失敗!')}} el.addEventListener(eventType, copyHandler)
}function legacyCopy(textToCopy: string) {const textarea = document.createElement('textarea')textarea.value = textToCopytextarea.style.position = 'fixed'document.body.appendChild(textarea)textarea.select()if (!document.execCommand('copy')) {throw new Error('execCommand 執行失敗')} document.body.removeChild(textarea)
}
const vCopy: Directive = {mounted(el: HTMLElement, binding:DirectiveBinding) {addEventListener(el, binding)},updated(el: HTMLElement, binding:DirectiveBinding) {const { value } = bindingel.setAttribute('copyValue', String(value))},
}
export const setupCopyDirective = (app: App<Element>) => {app.directive('copy', vCopy)
}
export default vCopy
2.v-focus
import type { Directive ,App} from 'vue'const vFocus: Directive = {mounted(el: HTMLElement) {console.log(el,'el');el.focus && el.focus()},updated(el: HTMLElement) {el.focus && el.focus()},
}
export const setupFocusDirective = (app: App<Element>) => {app.directive('focus', vFocus)
}
export default vFocus
組件中使用
<script setup lang="ts">import {ref} from "vue";import { BaseButton } from '@/components/Button'import { ElInput } from 'element-plus'const value = ref<string>('我是要復制的值')const change = ref<string>('我是要改變的值')
</script><template><button v-copy.dblclick="value">點擊我復制</button><BaseButton type="primary" class="w-[20%]" v-copy:復制成功了.dblclick="value">點擊我復制</BaseButton><el-input v-model="change" placeholder="Please input" /><BaseButton type="primary" class="w-[20%]" @click="() => value = change">改變將要復制的值</BaseButton><input v-model="value" placeholder="111" v-focus />
</template><style scoped></style>