vue自定義指令的創建和使用


一、自定義指令的創建和使用

Vue自帶的指令很多,v-for/v-if/v-else/v-else-if/v-model/v-bind/v-on/v-show/v-html/v-text...
但是這些指令都是比較偏向於工具化,有些時候在實現具體的業務邏輯的時候,發現不夠用,如何來自定義指令.


1、自定義指令
①創建
new Vue({
  directives:{
    change:{
      bind:function(){},
      update:function(){},
      unbind:function(){}
    }
  }
})

在自定義指令時,在指令對應的配置對象中有3個處理函數指令對應的操作
bind
  指令在綁定到元素要執行的操作
update
  如果在調用指令時候,傳了參數,當參數變化時候,就會執行update所指定的方法
unbind
  解綁要執行的操作

②使用自定義指令
directives:{
  hello:{
    bind:function(){},
    update:function(){},
    unbind:function(){}
  }
}

使用:
  v-hello

注意事項:
建議在給指令的命名采用小駝峰式的命名方式,比如changeBackgroundColor,在使用的時候,采用烤串式寫法 v-change-background-color

(方法:參數,返回值)

bind方法以及update方法 都是有參數的,
一個是el,對應的是調用指令的元素
一個bindings,是一個對象:name/rawName/value/oldValue...

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <script src="js/vue.js"></script>
    <title></title>
</head>
<body>

<div id="container">
    <p>{{msg}}</p>
    <!-- 准備實現需求: 在h1標簽上面,加上一個按鈕,當點擊按鈕時候,對count實現一次 自增操作,當count等於5的時候,在控制台輸出‘it is a test’ -->
    <button @click="handleClick">clickMe</button>
    <h1 v-if="count < 6" v-change="count">it is a custom directive</h1>
</div>

<script>
    //directive
    new Vue({ el: '#container', data: { msg: 'Hello Vue', count:0 }, methods:{ handleClick: function () { //按鈕單擊,count自增
                this.count++; } }, directives:{ change:{ bind: function (el,bindings) { console.log('指令已經綁定到元素了'); console.log(el); console.log(bindings); //准備將傳遞來的參數
                    // 顯示在調用該指令的元素的innerHTML
 el.innerHTML = bindings.value; }, update: function (el,bindings) { console.log('指令的數據有所變化'); console.log(el); console.log(bindings); el.innerHTML = bindings.value; if(bindings.value == 5) { console.log(' it is a test'); } }, unbind: function () { console.log('解除綁定了'); } } } }) </script>

</body>
</html>

 

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <script src="js/vue.js"></script>
    <title></title>
</head>
<body>

<div id="container">
    <p>{{msg}}</p>
    <h1 v-change-background-color="myBgColor"> it is a header1 </h1>
</div>

<script>
    new Vue({ el: '#container', data: { msg: 'Hello Vue', myBgColor:'#ff0000' }, directives:{ changeBackgroundColor:{ bind: function (el,bindings) { console.log('in bind '); console.log(bindings.value); el.style.backgroundColor = bindings.value; } } } }) </script>

</body>
</html>

 <h4 v-change-background-color="'red'">背景色</h4>這樣也是可以的,但是寫死了,不好


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM