如何在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屬性獲取