Vue 3自定義指令開(kāi)發(fā)的相關(guān)總結(jié)
什么是指令(directive)
在Angular和Vue中都有Directive的概念,我們通常講Directive 翻譯為“指令”。
在計(jì)算機(jī)技術(shù)中,指令是由指令集架構(gòu)定義的單個(gè)的CPU操作。在更廣泛的意義上,“指令”可以是任何可執(zhí)行程序的元素的表述,例如字節(jié)碼。
那么在前端框架Vue中“指令”到底是什么,他有什么作用呢?
在Vue開(kāi)發(fā)中我們?cè)谀0逯薪?jīng)常會(huì)使用v-model和v-show等以v-開(kāi)頭的關(guān)鍵字,這些關(guān)鍵字就是Vue框架內(nèi)置的指令。通過(guò)使用v-model,可以獲取實(shí)現(xiàn)DOM和數(shù)據(jù)的綁定;使用v-show,可以控制DOM元素顯示。簡(jiǎn)而言之通過(guò)使用這些模板上的標(biāo)簽,讓框架對(duì)DOM元素進(jìn)行了指定的處理,同時(shí)DOM改變后框架可以同時(shí)更新指定數(shù)據(jù)。指令是Vue MVVM的基礎(chǔ)之一。
指令的使用場(chǎng)景
除了使用內(nèi)置的指令,Vue同樣支持自定義指令,以下場(chǎng)景可以考慮通過(guò)自定義指令實(shí)現(xiàn):
DOM的基礎(chǔ)操作,當(dāng)組件中的一些處理無(wú)法用現(xiàn)有指令實(shí)現(xiàn),可以自定義指令實(shí)現(xiàn)。例如組件水印,自動(dòng)focus。相對(duì)于用ref獲取DOM操作,封裝指令更加符合MVVM的架構(gòu),M和V不直接交互。
<p v-highlight="'yellow'">Highlight this text bright yellow</p>
多組件可用的通用操作,通過(guò)使用組件(Component)可以很好的實(shí)現(xiàn)復(fù)用,同樣通過(guò)使用組件也可以實(shí)現(xiàn)功能在組件上的復(fù)用。例如拼寫(xiě)檢查、圖片懶加載。使用組件,只要在需要拼寫(xiě)檢查的輸入組件上加上標(biāo)簽,遍可為組件注入拼寫(xiě)檢查的功能,無(wú)需再針對(duì)不同組件封裝新的支持拼寫(xiě)功能呢。
Vue 3如何自定義指令
Vue支持全局注冊(cè)和局部注冊(cè)指令。
全局注冊(cè)注冊(cè)通過(guò)app實(shí)例的directive方法進(jìn)行注冊(cè)。
let app = createApp(App) app.directive('highlight', { beforeMount(el, binding, vnode) { el.style.background = binding.value } })
局部注冊(cè)通過(guò)給組件設(shè)置directive屬性注冊(cè)
export default defineComponent({ name: "WebDesigner", components: { Designer, }, directives: { highlight: { beforeMount(el, binding, vnode) { el.style.background = binding.value; }, }, }, });
注冊(cè)組件包含組件的名字,需要唯一和組件的一個(gè)實(shí)現(xiàn)對(duì)象,組冊(cè)后即可在任何元素上使用了。
<p v-highlight="'yellow'">Highlight this text bright yellow</p>
自定義組件就是實(shí)現(xiàn)Vue提供的鉤子函數(shù),在Vue 3中鉤子函數(shù)的生命周期和組件的生命周期類似:
- created - 元素創(chuàng)建后,但是屬性和事件還沒(méi)有生效時(shí)調(diào)用。
- beforeMount- 僅調(diào)用一次,當(dāng)指令第一次綁定元素的時(shí)候。
- mounted- 元素被插入父元素時(shí)調(diào)用.
- beforeUpdate: 在元素自己更新之前調(diào)用
- Updated - 元素或者子元素更新之后調(diào)用.
- beforeUnmount: 元素卸載前調(diào)用.
- unmounted -當(dāng)指令卸載后調(diào)用,僅調(diào)用一次
每一個(gè)鉤子函數(shù)都有如下參數(shù):
- el: 指令綁定的元素,可以用來(lái)直接操作DOM
- binding: 數(shù)據(jù)對(duì)象,包含以下屬性
instance: 當(dāng)前組件的實(shí)例,一般推薦指令和組件無(wú)關(guān),如果有需要使用組件上下文ViewModel,可以從這里獲取
value: 指令的值,即上面示例中的“yellow“
oldValue: 指令的前一個(gè)值,在beforeUpdate和Updated 中,可以和value是相同的內(nèi)容。
arg: 傳給指令的參數(shù),例如v-on:click中的click。
modifiers: 包含修飾符的對(duì)象。例如v-on.stop:click 可以獲取到一個(gè){stop:true}的對(duì)象
- vnode: Vue 編譯生成的虛擬節(jié)點(diǎn),
- prevVNode: Update時(shí)的上一個(gè)虛擬節(jié)點(diǎn)
Vue 2 指令升級(jí)
指令在Vue3中是一個(gè)Breaking Change,指令的鉤子函數(shù)名稱和數(shù)量發(fā)生了變化。Vue3中為指令創(chuàng)建了更多的函數(shù),函數(shù)名稱和組件的生命周期一致,更易理解。
以下是變化介紹
另一個(gè)變化是組件上下文對(duì)象的獲取方式發(fā)生了變化。一般情況下推薦指令和組件實(shí)例相互獨(dú)立,從自定義指令內(nèi)部去訪問(wèn)組件實(shí)例,那可能說(shuō)明這里不需要封裝指令,指令就是組件本事的功能。但是可能的確有某些場(chǎng)景需要去獲取組件實(shí)例。
在Vue 2中通過(guò)vnode參數(shù)獲取
bind(el, binding, vnode) { const vm = vnode.context }
在Vue 3中 通過(guò)binding參數(shù)獲取
mounted(el, binding, vnode) { const vm = binding.instance }
Vue 3 自定義指令實(shí)例 – 輸入拼寫(xiě)檢查
這里使用Plugin的方式注入指令。
新建SpellCheckPlugin.ts,聲明插件,在插件的install方法中注入指令
import { App } from 'vue' function SpellCheckMain(app: App, options: any) { // } export default { install: SpellCheckMain }
SpellCheckMain方法實(shí)現(xiàn)組件以及,拼寫(xiě)檢查方法,具體拼寫(xiě)檢查規(guī)則可以根據(jù)業(yè)務(wù)或者使用其他插件方法實(shí)現(xiàn)
function SpellCheckMain(app: App, options: any) { const SpellCheckAttribute = "spell-check-el"; let SpellCheckTimer: Map<string, number> = new Map(); let checkerId = 0; function checkElement(el: HTMLElement) { let attr = el.getAttribute(SpellCheckAttribute); if (attr) { clearTimeout(SpellCheckTimer.get(attr)); let timer = setTimeout(() => { checkElementAsync(el) }, 500); SpellCheckTimer.set(attr, timer) } } function checkText(words?: string | null): [string?] { if (!words) { return []; } let errorWordList: [string?] = []; try { let wordsList = words.match(/[a-zA-Z]+/ig); wordsList?.forEach((word) => { if (!checkWord(word)) { errorWordList.push(word); } }) } catch { } return errorWordList; } function checkWord(text: string) { //模擬拼寫(xiě)檢查,這里使用其他檢查庫(kù) return text.length > 6 ? false : true; } function checkElementAsync(el: HTMLElement) { let text = (el as HTMLInputElement).value || el.innerText; let result = checkText(text); let attr = el.getAttribute(SpellCheckAttribute); if (!attr) { return; } if (result && result.length) { el.style.background = "pink" let div = document.getElementById(attr); if (!div) { div = document.createElement("div"); div.id = attr; div.style.position = "absolute" div.style.top = "0px" div.style.left = el.clientWidth + "px" if (el.parentElement) { el.parentElement.style.position = "relative" if (el.parentElement.lastChild === el) { el.parentElement.appendChild(div); } else { el.parentElement.insertBefore(div, el.nextSibling); } } } div.innerHTML = result.length.toString() + " - " + result.join(","); } else { el.style.background = ""; let div = document.getElementById(attr); if (div) { div.innerHTML = "" } } console.log(result) } app.directive('spell-check', { created() { console.log("created", arguments) }, mounted: function (el, binding, vnode, oldVnode) { console.log("mounted", arguments) //set checker id for parent let attr = "spellcheck-" + (checkerId++); el.setAttribute(SpellCheckAttribute, attr); console.log("attr", attr) if (el.tagName.toUpperCase() === "DIV") { el.addEventListener("blur", function () { checkElement(el) }, false); } if (el.tagName.toUpperCase() === "INPUT") { el.addEventListener("keyup", function () { checkElement(el) }, false); } // el.addEventListener("focus", function () { // checkElement(el) // }, false); }, updated: function (el) { console.log("componentUpdated", arguments) checkElement(el); }, unmounted: function (el) { console.log("unmounted", arguments) let attr = el.getAttribute(SpellCheckAttribute); if (attr) { let div = document.getElementById(attr); if (div) { div.remove(); } } } }) }
main.ts中使用插件
/// <reference path="./vue-app.d.ts" /> import { createApp } from 'vue' import App from './App.vue' import router from './router' import SpellCheckPlugin from './plugins/SpellCheckPlugin' let app = createApp(App) app.use(SpellCheckPlugin) app.use(router).mount('#app')
組件中直接使用指令即可
<template> <div ref="ssHost" style="width: 100%; height: 600px"></div> <div><div ref="fbHost" spell-check v-spell-check="true" contenteditable="true" spellcheck="false" style="border: 1px solid #808080;width:600px;"></div></div> <div><input v-model="value1" v-spell-check spellcheck="false" style="width:200px;" /></div> </template>
結(jié)合在使用SpreadJS上 ,基于檢查用戶拼寫(xiě)輸入的功能,效果如下圖:
以上就是Vue 3自定義指令開(kāi)發(fā)的相關(guān)總結(jié)的詳細(xì)內(nèi)容,更多關(guān)于Vue 3自定義指令開(kāi)發(fā)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Vue項(xiàng)目打包成exe可執(zhí)行文件的實(shí)現(xiàn)過(guò)程(無(wú)瑕疵,完美版)
突然接到公司需求,說(shuō)客戶想讓我們把項(xiàng)目直接打包,所以下面這篇文章主要給大家介紹了關(guān)于Vue項(xiàng)目打包成exe可執(zhí)行文件的實(shí)現(xiàn)過(guò)程,文中通過(guò)圖文介紹的非常詳細(xì),需要的朋友可以參考下2022-11-11關(guān)于Element?table組件滾動(dòng)條不顯示的踩坑記錄
這篇文章主要介紹了關(guān)于Element?table組件滾動(dòng)條不顯示的踩坑記錄,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-08-08vue $refs動(dòng)態(tài)拼接獲取值問(wèn)題
這篇文章主要介紹了vue $refs動(dòng)態(tài)拼接獲取值問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01vue的簡(jiǎn)介及@vue/cli?腳手架的使用示例
vue 是一個(gè) 漸進(jìn)式的javascript框架,腳手架是一個(gè)通用概念,幫助搭建項(xiàng)目的工具,本文以vue2為例結(jié)合實(shí)例代碼給大家詳細(xì)講解,感興趣的朋友跟隨小編一起看看吧2022-12-12el-checkbox-group?的v-model無(wú)法綁定對(duì)象數(shù)組的問(wèn)題解決
elementUI官方文檔中el-checkbox-group組件綁定的都為一維數(shù)組,本文主要介紹了解決el-checkbox-group?的v-model無(wú)法綁定對(duì)象數(shù)組,感興趣的可以了解一下2023-05-05