Vue中,获取Dom节点的3种方式
Vue本来无需操作DOM来更新界面,而且Vue也不推荐我们直接操作DOM,但是我们非要拿到DOM操作DOM怎么办,那也是有方法的,而且不止一种方法
方式一:(事件源) <body> <div id="aa"> <input type="button" value="点击" v-on:click=fun/> </div> <script> new Vue({ el:#aa, methods:{ fun:function(event){ console.log(event.target); } } }) </script> </body> 输出结果 当然也可以在方法中传参进去: <body> <div id="aa"> <input type="button" value="点击" v-on:click=fun($event.target)/> </div> <script> new Vue({ el:#aa, methods:{ fun(x){ console.log(x); } } }) </script> </body>
方式二:(使用ref) <body> <div id="aa"> <input ref=name type="button" value="点击" v-on:click=fun/> </div> <script> new Vue({ el:#aa, methods:{ fun(){ console.log(this.$refs.name); } } }) </script> </body> 输出结果:
方式三:(自定义全局指令) <body> <div id="aa"> <input type="button" value="点击" v-get/> </div> <script> Vue.directive("get",{ bind:function(el){ console.log(el); } }) new Vue({ el:#aa }) </script> </body> 这里不用点击,就可以获取元素,好像在谷歌显示不友好, 在火狐显示会好点