X

XiaoSong

V1

2023/01/13阅读:27主题:默认主题

Vue使用技巧,nextTick的使用

使用方式如下:

<template>
    <div>
        <ul ref="ulRef">
            <li v-for="(item, index) in list" :key="index">
                {{ item }}
            </li>
        </ul>
        <button @click="addLi">添加</button>
    </div>
</template>
<script setup>
import {nextTick, ref} from 'vue'

const list = ref(['Vue''React''Angular'])
const ulRef = ref(null// Vue3获取dom的方式
  
const addLi = () => {
    // 添加数组项
    list.value.push('JS')
    // 获取子元素个数
    const length = ulRef.value.children.length
    console.log('length:', length)
}
</script>

运行效果如下:

理论上来讲当我们点击添加的时候会增加一个li, console.log('length:', length)应该输出length: 4。 但是当我们点击添加后会发现输出的是length: 3

使用nextTick改造之后的代码:

<script setup>
import {nextTick, ref} from 'vue'

const list = ref(['Vue''React''Angular'])
const ulRef = ref(null)

const addLi = () => {

    list.value.push('JS')
    nextTick(() => { 
        // 获取子元素个数
        const length = ulRef.value.children.length
        console.log('length:', length)
    })
}
</script>

改造完之后就会输出预期的值了。

分类:

前端

标签:

前端

作者介绍

X
XiaoSong
V1