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

Vue3中结合computed使用时如何获取template ref实现input聚焦?

实现聚焦功能的方案

你不需要纠结额外声明ref是否冗余,这是Vue3组合式API中操作模板DOM的标准推荐写法,只要注意避免和你现有计算属性name重名即可,具体实现如下:


方案1:显式声明模板ref(最推荐,生产环境优先用)

<template>
    <!-- 修改模板ref的名称,避免和计算属性name冲突 -->
    <input ref="nameInput" :value="name" />
 </template>
    
 <script>
    import {ref, computed, onMounted} from 'vue';
    export default {
      props: ['name'],
      setup(props) {
        const name = computed(() => someTextPrepare(props.name));
        // 声明模板ref绑定的变量
        const nameInput = ref(null);

        // 示例:组件挂载后自动聚焦,你也可以在任意需要触发聚焦的时机调用
        onMounted(() => {
          // 可选链避免DOM未完成渲染时报错
          nameInput.value?.focus();
        });

        // 必须将nameInput返回,模板才能完成绑定
        return { name, nameInput };
      }
    }
</script>

这种写法逻辑清晰、支持完整的TypeScript类型提示,后续需要操作input的其他DOM属性也可以直接复用这个ref,属于最优雅的可维护方案。


方案2:精简写法(仅适合临时调试,不推荐生产用)

如果你不想额外声明变量返回,也可以通过getCurrentInstance获取组件实例访问$refs,但这种写法丢失类型提示,不符合组合式API的设计规范:

<script>
import {ref, computed, onMounted, getCurrentInstance} from 'vue';
export default {
  props: ['name'],
  setup(props) {
    const name = computed(() => someTextPrepare(props.name));
    const instance = getCurrentInstance();

    onMounted(() => {
      instance?.refs.name?.focus();
    });

    return { name };
  }
}
</script>

内容的提问来源于stack exchange,提问作者Roman Sarvarov

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 08:15:03