---
# System prepended metadata

title: directive 自訂義指令 (5-7)
tags: [5. 進階Api, Vue]

---

# directive 自訂義指令 (5-7)
###### tags: `Vue`、`5. 進階Api`
2022.3.7



**&emsp;&emsp;此可以引用網路上人家寫好的方法。**

### 範例1：自訂義方法套用ＣＳＳ
```
<div id="app">
        <input type="text" v-addclass="'form-control'">
</div>

<script>
        const app = Vue.createApp({
            data(){
                return{
                    text:'自定義v-方法',
                }
            }
        });

        app.directive('addclass',{
            mounted(el,binding){
                el.className = binding.value
            }
        })

        app.mount('#app');
</script>
```

範例2：驗證是否為Email格式
```
    <div id="app">
        <input type="text" v-model="text" class="form-control" v-valemail>
    </div>

    <script>
        const app = Vue.createApp({
            data(){
                return{
                    text:'自定義v-方法',
                }
            }
        });

        app.directive('valemail',{
            updated: function(el,binding,vnode){
                //el:元素本體
                //binding:綁定資料狀態
                //vnode:虛擬Dom節點
                
                //----------------取得所輸入內容--------------
                const currentModel = Object.keys(binding.instance)[0]; 
                const value = binding.instance[currentModel];
                //-------------------------------------------

                //----------判斷輸入內容是否為EMAIL格式--------
                const className = 'form-control' 
                const re = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i; //Email格式
                if(!re.test(value)){
                    el.className = `${className} is-invalid`
                    console.log(el.className)
                }
                else{
                    el.className = `${className} is-valid`
                    console.log(el.className)
                }
                //--------------------------------------------
            }
        });

        app.mount('#app');
    </script>
```