在vue中如何获取元素

如何在vue中获取元素的dom节点

  1. 在vue的生命周期mounted的时候就已经渲染了dom节点

简单粗暴

<script>
    mouted(){
    let elm = this.$el.querySelctor('#id)
}
        
    
</script>
  1. 使用ref 来获取

    <div ref='box' @click='handClick'>123</div>
    <script>
    	export default{
    		methods:{
    	 		hangClick(){
    	 			console.log(this.$refs.box)
    	 		}
    	}
    	}
    </script>
    
    1. 使用原生
    	<div class="box" @click="handClick">box</div>
    
    
    
               handClick(){
                    var box = document.getElementsByClassName('box')[0]
                    console.log(box);
     }
    

    在vue中尽量减少操作操作dom元素,建议选用ref属性获取

posted @ 2022-04-18 23:27  张尊娟  阅读(2403)  评论(0编辑  收藏  举报