自定義指令好處不少,有時候不少簡單的功能形不成方法,可是調用的地方有不少,這時候使用自定義指令實際上是一個不錯的選擇,下面就是一個簡單的自定義指令實現一個倒置時:
看圖html
<!DOCTYPE html> <html lang="en"> <head> <title></title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://unpkg.com/vue"></script> </head> <body> <div id="app"> <button v-countdown='5'>click</button> <br/> </div> </body> <script> function countdownTime(binding) { let time = binding.value || 10; let timer = setInterval(function () { if (time > 1) { --time; binding.elm.innerHTML = "倒置時還有:" + time + "(秒)"; } else { binding.elm.innerHTML = "click"; clearInterval(timer); } }, 1000); } Vue.directive('countdown', { bind(el, vnode, binding) { el.addEventListener("click", function () { countdownTime(binding); }); }, unbind(el, binding) { el.removeEventListener("click", countdownTime(binding)); } }); var vm = new Vue({ el: "#app", }); </script> </html>
github地址:https://github.com/wqb2017/my...vue