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

Vue3(Nuxt)中如何动态渲染file类型input的选中文件名?

问题解决:Nuxt中文件输入框选中文件名后页面不更新

你的代码核心问题是错误覆盖了ref响应式对象,导致页面无法感知变量变化,具体修正方案如下:

错误根源

用ref创建的响应式变量fileName,必须通过.value属性修改值才能触发响应式更新。你直接写fileName = file.files[0].name,相当于把原本的ref对象替换成了普通字符串,彻底丢失了响应式能力。

修正后的完整代码

Script 部分

<script setup>
const inputField = ref(null);
// 用const声明ref变量,避免意外覆盖
const fileName = ref('');

function changeFileName(file) {
  // 用可选链操作符避免空值报错
  if (file.files?.[0]) {
    fileName.value = file.files[0].name;
  } else {
    fileName.value = '';
  }
}
</script>

Template 部分

<template>
  <div>
    <b>{{ fileName }}</b>
    <!-- 直接通过$event.target获取文件输入框元素,无需传ref -->
    <input
      type="file"
      ref="inputField"
      @change="changeFileName($event.target)"
      style="opacity: 0;"
    />
    <!-- 可选:添加可见按钮触发选择,优化无感知输入框的交互体验 -->
    <button @click="inputField?.click()">选择文件</button>
  </div>
</template>

额外优化提示

由于你把原生输入框设为透明,建议添加一个可见的触发按钮,引导用户操作,避免出现交互盲区。

内容的提问来源于stack exchange,提问作者Mehmet Ali KOÇAL

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 00:45:03