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

Vue行内编辑组件编辑后如何更新绑定值?

Vue行内编辑组件值不更新的问题解决

你的组件出现值不更新的问题,核心原因有三个:

  • 单向绑定无法同步输入值:输入框用了:value="computedCellValue"单向绑定,输入内容的变化不会反向更新cellValue,而且Vue规定props是只读的,不能直接修改父组件传递的props。
  • 缺少编辑状态的临时存储:直接依赖props.cellValue作为输入框的值,编辑过程中如果父组件数据变化会干扰编辑,同时输入的新值没有临时存储的地方。
  • 未触发父组件数据更新:编辑完成后没有把新值传递给父组件,导致父组件的数据源没变化,自然cellValue不会更新。

修改后的完整代码

<script setup>
import { defineProps, defineEmits, ref, nextTick } from 'vue';

const props = defineProps([
    "cellValue",
    "prefix",
    "postfix"
]);
// 定义自定义事件,用于通知父组件更新值
const emit = defineEmits(['update:cellValue']);

const isEditing = ref(false);
const inputField = ref(null);
// 临时存储编辑时的输入值,避免直接操作props
const editValue = ref('');

function toggleEditOn() {
    isEditing.value = true;
    // 进入编辑模式时,把当前cellValue同步到临时变量
    editValue.value = props.cellValue;
    
    nextTick(() => {
        inputField.value.focus();
        inputField.value.select();
    });
}

function toggleEditOff() {
    isEditing.value = false;
    // 编辑完成后,通过自定义事件把新值传递给父组件
    emit('update:cellValue', editValue.value);
}
</script>

<template>
    <td class="w-64 mx-1" @dblclick="toggleEditOn()" v-show="!isEditing">
        {{ prefix }}{{ cellValue }}{{ postfix }}
    </td>
    <td class="w-64 mx-1" v-show="isEditing">
        {{ prefix }}
        <input 
            class="w-64 bg-slate-400 p-1 text-white" 
            ref="inputField" 
            type="text" 
            v-model="editValue" 
            @blur="toggleEditOff()" 
            @keyup.enter="toggleEditOff()"
        >
        {{ postfix }}
    </td>
</template>

父组件使用方式

父组件需要通过v-model:cellValue来绑定数据,这样组件内部的emit('update:cellValue')会自动更新父组件的数据源:

<InlineEdit v-model:cellValue="yourData.value" prefix="[" postfix="]" />

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 16:40:15