溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Vue自定義指令如何使用

發(fā)布時間:2023-04-18 09:48:16 來源:億速云 閱讀:113 作者:iii 欄目:開發(fā)技術(shù)

這篇“Vue自定義指令如何使用”文章的知識點大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細,步驟清晰,具有一定的借鑒價值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“Vue自定義指令如何使用”文章吧。

    何為自定義指令

    通過前面的學(xué)習(xí),我們都有了一定的Vue知識,我們都知道可以在Vue實例創(chuàng)建后,在template標(biāo)簽中寫我們的界面,當(dāng)我們需要控制某個dom元素的顯示或者隱藏時,我們可以使用v-if指令。循環(huán)打印一個列表時,我們可以使用v-for指令等…,然而這些指令都是Vue給我們提供的,我們其實可以自己定義我們的指令,其實我理解這個自定義指令就是把某個功能做一個封裝,以這個指令提供給調(diào)用者使用。減少相同代碼的重復(fù)編寫。在Vue中,自定義指令可以有全局定義和局部定義兩種方式,下面我們一起看下如何定義自定義指令

    實例解析

    1.基本知識介紹

    我們以一個簡單的輸入框自動焦的例子來演示Vue的自定義指令,具體的場景是:界面中有一個輸入框,當(dāng)界面加載出來后,讓輸入框自動獲取焦點,我們先看下一般的實現(xiàn)方法,代碼如下:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-
        scale=1.0">
        <title>自定義指令</title>
        <script src="https://unpkg.com/vue@next"></script>
    </head>
    <body>
        <div id="root"></div>
    </body>
    <script>
     const app = Vue.createApp({
        mounted(){
            this.$refs.input.focus();
        },
            template: 
            `
            <div>
                <input ref="input"/>
            </div>
            `
        });
        const vm = app.mount('#root');
    </script>

    運行結(jié)果讀者可以自己運行看下效果,然后去掉focus函數(shù)調(diào)用,再運行看效果

    我們在輸入框中使用ref屬性的方式,當(dāng)頁面加載完后,使用this.$refs.input.focus(),獲取到input輸入框,然后調(diào)用focus方法讓輸入框獲取焦點。

    使用上面的方法雖然能完成我們的需求,但是寫起來比較麻煩,而且需要在我們的app實例的mounted()方法中增加聚焦的邏輯,使用自定義指令可以更簡單的實現(xiàn)上面的輸入框自動獲取焦點的功能,代碼如下:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-
        scale=1.0">
        <title>自定義指令</title>
        <script src="https://unpkg.com/vue@next"></script>
    </head>
    <body>
        <div id="root"></div>
    </body>
    <script>
     const app = Vue.createApp({
           data(){
            return{
                display:true
            	}
           },
            template: 
            `
            <div v-show="display">
                <input v-focus/>
            </div>
            `
        });
        // 定義全局的自定義指令
        app.directive('focus',{
            mounted(el){
                console.log(el);
                el.focus();
                console.log('mounted');
            }
        });
        const vm = app.mount('#root');
    </script>

    如上面代碼所示,使用app.directive(&lsquo;指令名稱&rsquo;,{ xxxx});的方式可以自定義的指令,使用時在對應(yīng)的dom元素上添加v-指令名稱就可以了,就如本例子中,調(diào)用的方法如下:

    <input v-focus/>

    這時候運行代碼會發(fā)現(xiàn)效果和我們之前做的一模一樣,這個寫法更簡單。在文中我們看到了mounted函數(shù),這個函數(shù)是Vue生命周期的函數(shù)嗎,意思是當(dāng)界面掛載完成時會回調(diào)它,el參數(shù)就是我們使用自定義指令的那個Dom元素

     mounted(el){
                console.log(el);
                el.focus();
                console.log('mounted');
            }

    其實定義自定義指令時不只可以重寫mounted()函數(shù),還可以重寫其他的函數(shù),如下所示:

        app.directive('focus',{
            beforeMount(el){
                console.log('beforeMount');
            },
            mounted(el){
                console.log('mounted');
            },
            beforeUpdate(){
                console.log('beforeUpdate');
            },
            updated(){
                console.log('updated');
            },
            beforeUnmount(){
                console.log('beforeUnmount');
            },
            unmounted(){
                console.log('unmounted');
            }
        });

    在瀏覽器中運行上面代碼,打開console,如下

    Vue自定義指令如何使用

    我們可以在對應(yīng)的生命周期回調(diào)中做對應(yīng)的事情。

    在上面的代碼中我們定義自定義指令用的是全局的方式,其實我們還有局部的方式,代碼如下:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-
        scale=1.0">
        <title>自定義指令</title>
        <script src="https://unpkg.com/vue@next"></script>
    </head>
    <body>
        <div id="root"></div>
    </body>
    <script>
     const direc = {
          focus:{
                mounted(el){
                   el.focus();
                }
            }
        };
     const app = Vue.createApp({
           data(){
            return{
                display:true
            }
           },
           directives:direc,
            template: 
            `
            <div v-show="display">
                <input v-focus/>
            </div>
            `
        });
         const vm = app.mount('#root');
    </script>

    使用局部定義自定義屬性的方式是:

     const direc = {
          focus:{
                mounted(el){
                   el.focus();
                }
            }
        };

    然后使用的時候需要加上:

     const app = Vue.createApp({
       ...
           directives:direc,
       ...
        });

    2.使用自定義指令實現(xiàn)改變輸入框位置

    我們接下來使用Vue的自定義指令實現(xiàn)一個小功能,就是動態(tài)改變輸入框的位置,代碼如下:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-
        scale=1.0">
        <title>自定義指令</title>
        <style>
            .header{
                position: absolute;
            }
        </style>
        <script src="https://unpkg.com/vue@next"></script>
    </head>
    <body>
        <div id="root"></div>
    </body>
    <script>
     const app = Vue.createApp({
        data(){
            return{
                pxValue:50
            }  
        },
            template: 
            `
            <div>
                <div v-pos:left="pxValue" class="header">
                <input />
                </div>
            </div>
            `
        });
        app.directive('pos',{
            mounted(el,binding){
                el.style[binding.arg] = binding.value + 'px';
            },
            updated(el,binding){
                el.style[binding.arg] = binding.value + 'px';
            }  
        });
        // 上面代碼等價于下面注釋掉的代碼
        // app.directive('pos',(el,binding)=>{
        //     console.log(binding.arg,'binding')
        //     el.style[binding.arg]=(binding.value+'px');
        // })
        const vm = app.mount('#root');
    </script>

    首先我們定義一個樣式,使用絕對定位的方式確定輸入框的位置:

        <style>
            .header{
                position: absolute;
            }
        </style>

    使用一個pxValue表示輸入框位置的值,然后可以通過

    v-pos:left="pxValue"的方式確定輸入框是距離左邊還是右邊或者距離其他參照物。然后自定義指令的時候,拿到屬性傳過來的值和pxValue,改變輸入框位置:

      app.directive('pos',{
            mounted(el,binding){
                el.style[binding.arg] = binding.value + 'px';
            },
            updated(el,binding){
                el.style[binding.arg] = binding.value + 'px';
            }  
        });

    這里也可以寫成:

       app.directive('pos',(el,binding)=>{
            console.log(binding.arg,'binding')
            el.style[binding.arg]=(binding.value+'px');
        })

    然后使用的時候就可以如下:

     <div v-pos:left="pxValue" class="header">
    或者  <div v-pos:right="pxValue" class="header">
    或者  <div v-pos:top="pxValue" class="header">

    運行之后,可以修改對應(yīng)的值查看效果:

    Vue自定義指令如何使用

    以上就是關(guān)于“Vue自定義指令如何使用”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對大家有幫助,若想了解更多相關(guān)的知識內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道。

    向AI問一下細節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

    vue
    AI