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

Vue.js中如何修改作为Props传递的Ref值?

Vue子组件修改父组件Prop的正确方式

在Vue中,Props遵循单向数据流原则:子组件只能读取Prop,不能直接修改,否则会破坏组件间的状态一致性,这也是你触发TypeScript只读错误的原因。想要修改Prop的值,必须通过以下两种规范方式实现:

方式一:通过自定义事件通知父组件修改(推荐,适用于需要同步父组件状态的场景)

子组件通过defineEmits定义自定义事件,将修改请求发送给父组件,由父组件自行更新对应的状态。

修改后的子组件代码:

<template>
    <h1>{{ count }}</h1>
    <button @click="handleIncrement">+1</button>
</template>

<script setup lang="ts">
const props = defineProps({
    count: { type: Number, required: true }
});
// 定义自定义事件
const emit = defineEmits(['update:count']);

const handleIncrement = () => {
    // 向父组件发送修改请求,传递新值
    emit('update:count', props.count + 1);
};
</script>

修改后的父组件代码:

父组件监听子组件的自定义事件,更新自身的parentCount状态:

<template>
    <!-- 监听自定义事件,更新父组件状态 -->
    <ChildComponent :count="parentCount" @update:count="parentCount = $event"></ChildComponent>
</template>

<script setup lang="ts">
import { ref } from 'vue';
const parentCount = ref(0);
</script>

简化写法(v-model语法糖)

如果是Vue 3,还可以用v-model的语法糖简化代码,父组件可以直接写成:

<template>
    <ChildComponent v-model:count="parentCount"></ChildComponent>
</template>

子组件无需额外修改,只要保证事件名称遵循update:PropName的格式即可。

方式二:在子组件内创建本地副本(仅适用于无需同步回父组件的场景)

如果子组件只需要基于Prop的值做本地修改,不需要同步到父组件,可以在子组件内创建一个本地的ref变量,将Prop的值作为初始值:

<template>
    <h1>{{ localCount }}</h1>
    <button @click="localCount++">+1</button>
</template>

<script setup lang="ts">
import { ref } from 'vue';
const props = defineProps({
    count: { type: Number, required: true }
});
// 创建本地副本,初始值为Prop的count
const localCount = ref(props.count);
</script>

注意:这种方式下,父组件的parentCount更新时,子组件的localCount不会自动同步。如果需要同步,需要添加watch监听Prop的变化:

import { ref, watch } from 'vue';
// ...
watch(() => props.count, (newVal) => {
    localCount.value = newVal;
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 12:07:08