this.$nextTick()方法的使用

<div id="app">
      <h1 id="myh">{{msg}}</h1>
      <button @click="change">点击</button>
    </div>
    <script>
      var vm = new Vue({
        el: '#app',
        data: {
          msg: 'hello'
        },
        methods: {
          change() {

            this.msg = 'itcast'
            // console.log(document.getElementById('myh').innerText); // 如果直接这样打印,打印出来的结果不是我们想要的itcast,而是hello,因为this.msg = ‘itcast’ 它是异步的
            this.$nextTick(() => {
              console.log(document.getElementById('myh').innerText)
            })
          }
        }
      })
    </script>

  

作用是:等你页面dom中的数据渲染完之后,再执行回调函数中的方法。

vue中数据和dom渲染由于是异步的

this.$nextTick()方法主要是用在随数据改变而改变的dom应用场景中,vue中数据和dom渲染由于是异步的,所以,要让dom结构随数据改变这样的操作都应该放进this.$nextTick()的回调函数中。created()中使用的方法时,dom还没有渲染,如果此时在该钩子函数中进行dom赋值数据(或者其它dom操作)时无异于徒劳,所以,此时this.$nextTick()就会被大量使用,而与created()对应的是mounted()的钩子函数则是在dom完全渲染后才开始渲染数据,所以在mounted()中操作dom基本不会存在渲染问题。

 

 

 

转:https://www.cnblogs.com/mushitianya/p/10510912.html

转:https://blog.csdn.net/gaoxin666/article/details/96143571

posted @ 2021-01-08 16:52  炽橙子  阅读(856)  评论(0编辑  收藏  举报