You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Vue组合式API的条件渲染中访问模板ref?

解决Vue中v-if条件渲染后获取DOM元素并设置焦点的问题

不用换reactive(),问题根源不是ref()的问题,而是Vue的响应式DOM更新是异步的——你修改isInputShow.value = true后,DOM不会立刻渲染出来,所以此时input.value还是null。下面给你几种可行的解决方法:

方法一:用nextTick()等待DOM更新完成

修改你的showInput函数,借助nextTick()等到DOM更新后再操作input元素:

import { ref, nextTick } from 'vue'

export default {
    setup() {
        const isInputShow = ref(false)
        const input = ref(null)

        const showInput = async () => {
            if(!isInputShow.value) {
                isInputShow.value = true
                await nextTick() // 等待Vue完成DOM更新
                input.value?.focus() // 给input设置焦点
            }
        }
        
        return{
            input,
            isInputShow,
            showInput
        }
    }
}

方法二:监听isInputShow的变化

通过watch监听isInputShow的状态,当它变为true时再设置焦点:

import { ref, watch, nextTick } from 'vue'

export default {
    setup() {
        const isInputShow = ref(false)
        const input = ref(null)

        const showInput = () => {
            if(!isInputShow.value) {
                isInputShow.value = true
            }
        }

        // 监听isInputShow的变化
        watch(isInputShow, async (newVal) => {
            if(newVal) {
                await nextTick()
                input.value?.focus()
            }
        })
        
        return{
            input,
            isInputShow,
            showInput
        }
    }
}

方法三:用模板ref的回调函数自动设置焦点

直接在模板里给input的ref绑定一个回调函数,当元素被渲染出来时自动触发焦点设置,这种方式不需要在setup里维护input的ref:

<template>
    <input
        v-if="isInputShow"
        :ref="el => { if(el) el.focus() }"
    >
    <button
        v-else
        @click="showInput"
    >Show input</button>
</template>
import { ref } from 'vue'

export default {
    setup() {
        const isInputShow = ref(false)

        const showInput = () => {
            if(!isInputShow.value) {
                isInputShow.value = true
            }
        }
        
        return{
            isInputShow,
            showInput
        }
    }
}

内容的提问来源于stack exchange,提问作者Nanto Work

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.30 23:00:24