在vue中如何获取元素
如何在vue中获取元素的dom节点
- 在vue的生命周期mounted的时候就已经渲染了dom节点
简单粗暴
<script>
mouted(){
let elm = this.$el.querySelctor('#id)
}
</script>
-
使用ref 来获取
<div ref='box' @click='handClick'>123</div> <script> export default{ methods:{ hangClick(){ console.log(this.$refs.box) } } } </script>
- 使用原生
<div class="box" @click="handClick">box</div> handClick(){ var box = document.getElementsByClassName('box')[0] console.log(box); }
在vue中尽量减少操作操作dom元素,建议选用ref属性获取