vue中nextTick 的两种解决方法

 像这种情况就可以使用 nextTick 解决 [推荐]

<template>
    <div>
        <h2>欢迎您!{
   
   { name }}</h2>
        <button @click="edit">编辑</button>
        <input ref="content" v-show="status" type="text" v-model="name">
    </div>
</template>

<script>
export default {
    name: "Home",
    data() {
        return {
            name: "张三",
            status: false
        }
    },
    methods: {
        edit() {
            this.status = !this.status;
            // 等待页面渲染完毕后执行
            this.$nextTick(() => {
                // 显示输入框后自动获取焦点
                this.$refs.content.focus();
                // 获取输入框显示状态
                console.log(this.$refs.content.style.display);
            })
        }
    }
}
</script>

注:当事件触发后,会分为两次执行 先执行 nextTick 外边的代码 然后等 DOM 更新完毕后,再执行 nextTick 里边的代码.

第二种: 使用定时器解决【不推荐】

当然 使用定时器延迟执行也能解决这个问题。

<template>
    <div>
        <h2>欢迎您!{
   
   { name }}</h2>
        <button @click="edit">编辑</button>
        <input ref="content" v-show="status" type="text" v-model="name">
    </div>
</template>

<script>
export default {
    name: "Home",
    data() {
        return {
            name: "张三",
            status: false
        }
    },
    methods: {
        edit() {
            this.status = !this.status;
            // 使用定时器延迟执行
            setTimeout(() => {
                // 显示输入框后自动获取焦点
                this.$refs.content.focus();
                // 获取输入框显示状态
                console.log(this.$refs.content.style.display);
            })
        }
    }
}
</script>

:不需要给定时器设置时间,这样可以等 DOM 更新完毕后立即执行。但是更推荐使用 nextTick 解决。


 

原创作者:吴小糖

创作时间:2023.5.7

猜你喜欢

转载自blog.csdn.net/xiaowude_boke/article/details/130544815
今日推荐