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

Vue 3结合vee-validate使用时axios请求返回值无法赋值给自定义输入组件

问题原因

  • 你调用useField时传入的initialValue仅在组件初始化阶段生效,不会响应后续props.value的更新。组件初始化时axios请求尚未返回,userInfo.name是空字符串,等接口返回数据更新后,useField管理的inputValue没有同步更新,所以组件没有展示最新值。
  • 模板中绑定属性时不需要加this前缀,:value="this.userInfo.name"的写法不规范,虽然不会直接导致报错,但建议修改为:value="userInfo.name"。

修复方案

修改CustomInput.vue的逻辑,新增对props.value的监听,值变化时手动同步到useField返回的inputValue:

<script>
import { useField } from 'vee-validate'
import { watch } from 'vue'
// 如果是Vue2.6及更早版本,从@vue/composition-api导入watch

export default {
  props: {
    type: {
      type: String,
      default: 'text'
    },
    value: {
      type: String,
      default: ''
    },
    name: {
      type: String,
      required: true
    },
    placeholder: {
      type: String,
      default: ''
    },
    inputClass: {
      type: String,
      default: ''
    },
    notRequired: {
      type: Boolean,
      default: false
    }
  },
  emits: ['input'],
  setup (props, { emit }) {
    const {
      value: inputValue,
      errorMessage,
      meta,
      handleBlur,
      handleChange
    } = useField(props.name, undefined, {
      initialValue: props.value
    })

    // 监听父组件传入的value变化,同步到表单控件
    watch(() => props.value, (newVal) => {
      if (newVal !== inputValue.value) {
        inputValue.value = newVal
      }
    })

    // 可选:监听控件输入变化,同步到父组件,实现v-model支持
    watch(inputValue, (newVal) => {
      emit('input', newVal)
    })

    return {
      errorMessage,
      inputValue,
      meta,
      handleBlur,
      handleChange
    }
  }
}
</script>

修改父组件的绑定写法:

<CustomInput
  type="text"
  name="surname"
  placeholder="surname"
  :value="userInfo.name"
  inputClass="form-control form-control-solid h-auto mb-1 mt-2"
/>
<!-- 配置v-model支持后可以简化为如下写法 -->
<!-- <CustomInput
  type="text"
  name="surname"
  placeholder="surname"
  v-model="userInfo.name"
  inputClass="form-control form-control-solid h-auto mb-1 mt-2"
/> -->

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 07:24:03