likes
comments
collection
share

【Vue】nextTick

作者站长头像
站长
· 阅读数 310

可运行完整代码

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title></title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
</head>
<body>
  <div id="app">
    <ul ref="ulRef">
      <li v-for="(item, index) in items" :key="index">
        {{ item }}
      </li>
    </ul>
    <button @click="add"> add </button>
  </div>
</body>
<script>
  var app = new Vue({
    el: '#app',
    data() {
      return{
        items: ['1', '2', '3']
      }
    },
    methods: {
      add() {
        this.items.push(Math.random())
        // dom 异步渲染结束后执行
        this.$nextTick(() => {
          const ul = this.$refs.ulRef
          const len = ul.childNodes.length
          console.log('len ', len)
        })
        
      }
    }
  })
</script>
</html>