$nextTick的使用

this.$nextTick方法用于更新数据后,马上进行dom操作,获取dom内容。

this.$nextTick是异步的。

更新数据后,视图是更新了,但是获取视图上的新数据的时候,却是原来的。这是就要用nextTick了。

例子:

<template>

<div>
     <p ref="test">{{testData}}</p>
</div>
</template>
<script>
export default {
  name: "Home",
  data () {
    return {
        testData:"原来的数据"
    };
  },
  mounted(){
      //更新数据
      this.testData = "新的数据";
      //更新完数据,进行dom操作,获取的还是原来的数据
      console.log(this.$refs.test.textContent); //原来的数据
      this.$nextTick(()=>{
          console.log(this.$refs.test.textContent); //新的数据
          
      })
      
  }
}

一些注意的地方:

1.this.$refs只能在mounted里使用

2.获取元素里的文字,是通过this.$refs.xxx.textContent

猜你喜欢

转载自www.cnblogs.com/luguankun/p/10867242.html