Vue父子组件v-model数据不更新致Laravel表单验证失败求助
解决Vue父子组件v-model数据同步问题
问题根源
子组件仅在初始化时从value props读取数据存入自身data,但后续输入变化时未将更新同步回父组件,导致父组件提交表单时campaign.reward_type仍为初始空值,触发Laravel验证错误。自定义组件使用v-model需遵循双向绑定规则:父组件通过value props传值,子组件通过input事件回传更新后的值。
解决方案:修改子组件实现双向绑定
方法一:使用计算属性实现双向绑定
通过计算属性代理value props,实现输入变化时自动同步父组件:
<template> <div> <div> <label>Product Name</label> <textarea id="reward_type.product" name="reward_type[product]" v-model="localProduct" placeholder="Type product name here" required ></textarea> </div> <div> <label>Product Value</label> <input type="number" id="reward_type.price" min="0" name="reward_type[price]" v-model="localPrice" required /> </div> <div> <label>Product Note</label> <textarea id="participants-note" name="reward_type[caption_note]" v-model="localCaptionNote" placeholder="Type note here" :required="isEditMode" ></textarea> </div> </div> </template> <script> export default { name: 'reward-type', props: { type: { type: String, required: false, default: '' }, value: { type: Object, required: true } }, computed: { localProduct: { get() { return this.value.product || '' }, set(val) { this.updateRewardType({ ...this.value, product: val }) } }, localPrice: { get() { return this.value.price || 0 }, set(val) { this.updateRewardType({ ...this.value, price: Number(val) }) } }, localCaptionNote: { get() { return this.value.caption_note || '' }, set(val) { this.updateRewardType({ ...this.value, caption_note: val }) } } }, methods: { updateRewardType(newVal) { this.$emit('input', newVal) } } } </script>
方法二:直接监听输入事件同步父组件
直接监听每个输入的input事件,构建更新后的reward_type对象并触发同步:
<template> <div> <div> <label>Product Name</label> <textarea id="reward_type.product" name="reward_type[product]" :value="value.product" @input="handleInput('product', $event.target.value)" placeholder="Type product name here" required ></textarea> </div> <div> <label>Product Value</label> <input type="number" id="reward_type.price" min="0" name="reward_type[price]" :value="value.price" @input="handleInput('price', Number($event.target.value))" required /> </div> <div> <label>Product Note</label> <textarea id="participants-note" name="reward_type[caption_note]" :value="value.caption_note" @input="handleInput('caption_note', $event.target.value)" placeholder="Type note here" :required="isEditMode" ></textarea> </div> </div> </template> <script> export default { name: 'reward-type', props: { type: { type: String, required: false, default: '' }, value: { type: Object, required: true } }, methods: { handleInput(field, val) { const updatedRewardType = { ...this.value, [field]: val } this.$emit('input', updatedRewardType) } } } </script>
父组件验证
父组件的v-model="campaign.reward_type"无需修改,子组件正确触发input事件后,父组件的campaign.reward_type会自动同步更新,提交表单时即可携带最新输入值,避免Laravel验证错误。
内容的提问来源于stack exchange,提问作者Zulkifli Raihan
相关产品推荐
相关产品推荐

