vue实现自定义的v-xxx指令
有时候,我会比较疑惑,v-show v-if这些指令都是怎么写出来的,那么今天我就和大家一起看一下,如何自己写一个自己的指令,比如就叫v-xxx指令吧。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script src="./js/vue.js"></script> </head> <body> <div id="app"> <input type="button" value="++" @click="countAdd"/> <input type="button" value="--" @click="countSub"/> {{count}} <h1 v-xxx="count">如果不++,看不见我</h1> </div> <script> var m = { count : 0 } var vm = new Vue({ el:"#app", data: m, methods:{ countAdd:function(){ this.count++; }, countSub:function(){ this.count--; } }, directives:{ xxx:{ bind:function(el,bindings){ console.log('binding......'); console.log(el,bindings); if(bindings.value > 0){ el.setAttribute('style','display:block'); }else{ el.setAttribute('style','display:none'); } }, update:function(el,bindings){ console.log('updating......'); console.log(el,bindings); if(bindings.value > 0){ el.setAttribute('style','display:block'); }else{ el.setAttribute('style','display:none'); } }, unbind:function(el,bindings){ } } } }) </script> </body> </html>
我们实现了一个指令 v-xxx
这个指令的功能是,当v-xxx绑定的值是0时候,隐藏v-xxx所在的控件,如果v-xxx绑定的大于0时,显示v-xxx所在的控件