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

Vue3使用<script setup>无法重置Ref?求解决方案

表单重置失败的解决方案

原代码存在的问题

  • test使用ref([])包裹键值对,语法错误,数组不能容纳key:value结构,应改为对象形式
  • 展开ref对象时直接用{...test},会得到{value: 目标对象}的结构,导致form的层级不符合预期
  • 重置函数中initialState未定义,无法作为重置的基准值

可行解决方案

方案1:基于reactive+Object.assign重置

<script setup>
import { reactive } from 'vue'

// 定义初始状态基准对象
const initialState = {
  id: null,
  nm: null,
  addrs: null,
  city: null,
  state: null
}

// 基于初始状态创建响应式表单对象
const form = reactive({...initialState})

const resetValue = () => {
  // 用初始状态覆盖当前表单值
  Object.assign(form, initialState)
  console.log(form.id) // 输出null,验证重置效果
}
</script>

方案2:基于ref直接替换value重置

如果偏好使用ref管理表单,可直接替换ref的value属性:

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

const initialState = {
  id: null,
  nm: null,
  addrs: null,
  city: null,
  state: null
}

const form = ref({...initialState})

const resetValue = () => {
  // 直接替换为新的初始状态对象
  form.value = {...initialState}
  console.log(form.value.id)
}
</script>

方案3:结合toRefs的场景(适合单独绑定属性)

如果需要在模板中单独绑定表单的每个属性,可使用toRefs解构:

<script setup>
import { reactive, toRefs } from 'vue'

const initialState = {
  id: null,
  nm: null,
  addrs: null,
  city: null,
  state: null
}

const form = reactive({...initialState})
// 解构出响应式的单个属性,方便模板绑定
const { id, nm, addrs, city, state } = toRefs(form)

const resetValue = () => {
  Object.assign(form, initialState)
}
</script>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 14:05:15