vue中dom操作

this.$el

当前组件最外层div

<template>
  <!-- <div class="hot-wrap" v-on:contextmenu.prevent = "create"> -->
  <div class="hot-wrap" @mousedown.self = "mousedownHandle">
    <hot ></hot>
    <form-panel ref="formPanel" @submit="change"></form-panel>
  </div>
</template>

...
mounted () {
    this.$nextTick(_ => {
      this.settingEl = this.$el  //<div class="hot-wrap">..</div>
      this.docEl = document
    })
  },
...

this.$refs

可以通过this.$refs获取持有注册过 ref 特性 的所有 DOM 元素和组件实例

(1)获取DOM元素

<div id="box" ref="box"></div>
let box = this.$refs.box // 等同于 let box = document.getElementById('box')

(2)获取组件组件实例

<child-component ref="child"></child-component>
this.$refs.child.fn() //fn为child-component组件实例中的方法
this.$refs.child.$el //获取child-component组件dom

this.$nextTick()

官方解释:将回调延迟到下次 DOM 更新循环之后执行。

一些需要等到dom渲染结束后才执行的操作(如获取元素宽,高),就用到this.$nextTick()

<div class="box" ref="box">
    <div v-for="(item,index) in list" :key="index" class="item">
      {{item}}
    </div>
  </div>
  <button @click="listChange">点我</button>
 data () {
    return {
      list: []
    }
  },
  methods: {
    listChange () {
      this.list = [1, 2, 3]
      // let H = this.$refs.box.offsetHeight
      // console.log(H) //0
      this.$nextTick(() =>{
        let H = this.$refs.box.offsetHeight
        console.log(H) //63
      })
    }
  }

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值