美文网首页
vue操作DOM

vue操作DOM

作者: 谢大见 | 来源:发表于2019-02-20 14:18 被阅读0次

无法避免的dom操作 this.$elthis.$ref

vue中也是允许进行dome操作的(但是不建议)

this.$el

this.$el是在mounted中才会出现的,在created的时候是没有的所以我们引用的时候

它指的是当前组件的的元素

mounted(){
    this.$el.addEventListener('touchstart', this.itemTouchStart)
    this.$el.addEventListener('touchmove', this.itemTouchMove)
    this.$el.addEventListener('touchend', this.itemTouchEnd)
}

ref

在vue中可以通过给标签加 ref 属性,就可以在js中利用ref去引用它,从而操作该dom元素,

<template>
  <div>
    <div id="box" ref="mybox"  v-on:click="changeText()">
      DEMO
    </div>
  </div>
</template>
 
<script>
export default {
  data () {
    return {
      
    }
  },
  mounted () {
     this.$refs.mybox.style.color = 'red';
  },
  methods:{
    changeText() {
        this.$refs.box.innerHTML = "改变盒子的文字";
    }
  }
 
}
</script>
 
<style scoped>
  #box {
    width: 100px;
    height: 100px;
    line-height: 100px;
    font-size: 20px;
    text-align: center;
    border: 1px solid black;
    margin: 50px; 
    color: yellow;
  }

关键词ref,this.$refs

this.$nextTick

官方解释:将回调延迟到下次 DOM 更新循环之后执行。在修改数据之后立即使用它,然后等待 DOM 更新。

在mounted的时候,如果你要获取的元素高度是动态由数据撑起来的需要使用this.$nextTick

mounted (){
    this.$nextTick(() => {
        this.$refs.index.style.paddingBottom = this.$refs.sus.clientHeight + 'px';
    });
}

相关文章

网友评论

      本文标题:vue操作DOM

      本文链接:https://www.haomeiwen.com/subject/xskhyqtx.html