當(dāng)前位置:首頁(yè) >  站長(zhǎng) >  編程技術(shù) >  正文

Vue 3自定義指令開(kāi)發(fā)的相關(guān)總結(jié)

 2021-03-10 17:00  來(lái)源: 腳本之家   我來(lái)投稿 撤稿糾錯(cuò)

  域名預(yù)訂/競(jìng)價(jià),好“米”不錯(cuò)過(guò)

這篇文章主要介紹了Vue 3自定義指令開(kāi)發(fā)的相關(guān)總結(jié),幫助大家更好的理解和使用vue框架,感興趣的朋友可以了解下

什么是指令(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不直接交互。

Highlight this text bright yellow

多組件可用的通用操作,通過(guò)使用組件(Component)可以很好的實(shí)現(xiàn)復(fù)用,同樣通過(guò)使用組件也可以實(shí)現(xiàn)功能在組件上的復(fù)用。例如拼寫檢查、圖片懶加載。使用組件,只要在需要拼寫檢查的輸入組件上加上標(biāo)簽,遍可為組件注入拼寫檢查的功能,無(wú)需再針對(duì)不同組件封裝新的支持拼寫功能呢。

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í)例 – 輸入拼寫檢查

這里使用Plugin的方式注入指令。

新建SpellCheckPlugin.ts,聲明插件,在插件的install方法中注入指令

import { App } from 'vue'
 
function SpellCheckMain(app: App, options: any) {
//
}
 
export default {
    install: SpellCheckMain
}

SpellCheckMain方法實(shí)現(xiàn)組件以及,拼寫檢查方法,具體拼寫檢查規(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) {
        //模擬拼寫檢查,這里使用其他檢查庫(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上 ,基于檢查用戶拼寫輸入的功能,效果如下圖:

以上就是Vue 3自定義指令開(kāi)發(fā)的相關(guān)總結(jié)的詳細(xì)內(nèi)容,更多關(guān)于Vue 3自定義指令開(kāi)發(fā)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!

來(lái)源:腳本之家

鏈接:https://www.jb51.net/article/205009.htm

申請(qǐng)創(chuàng)業(yè)報(bào)道,分享創(chuàng)業(yè)好點(diǎn)子。點(diǎn)擊此處,共同探討創(chuàng)業(yè)新機(jī)遇!

相關(guān)標(biāo)簽
vue.js

相關(guān)文章

  • vue集成一個(gè)支持圖片縮放拖拽的富文本編輯器

    文章主要介紹了vue集成一個(gè)支持圖片縮放拖拽的富文本編輯器,幫助大家更好的理解和使用vue框架,感興趣的朋友可以了解下。

    標(biāo)簽:
    vue.js
  • vue自定義組件實(shí)現(xiàn)雙向綁定

    這篇文章主要為大家詳細(xì)介紹了vue自定義組件實(shí)現(xiàn)雙向綁定,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

    標(biāo)簽:
    vue.js
  • Vue實(shí)現(xiàn)隨機(jī)驗(yàn)證碼功能

    這篇文章主要為大家詳細(xì)介紹了Vue實(shí)現(xiàn)隨機(jī)驗(yàn)證碼功能,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

    標(biāo)簽:
    vue.js
  • vue實(shí)現(xiàn)樹(shù)狀表格效果

    這篇文章主要為大家詳細(xì)介紹了vue實(shí)現(xiàn)樹(shù)狀表格效果,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

    標(biāo)簽:
    vue.js
  • vue添加自定義右鍵菜單的完整實(shí)例

    這篇文章主要給大家介紹了關(guān)于vue添加自定義右鍵菜單的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

    標(biāo)簽:
    vue.js

熱門排行

信息推薦