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

Vue中defineModel在onMounted内更新后值未变更问题咨询

问题:子组件onMounted中更新defineModel绑定值后立即打印仍为0的原因

在Vue3项目中,父组件通过v-model:counter将响应式变量绑定到子组件,子组件使用defineModel接收该绑定,但在子组件的onMounted钩子中更新值后立即打印,结果仍为初始值0。请问这是否属于预期行为,异常现象的原因是什么?

父组件代码

<template>
  <child v-model:counter="counter" />
</template>
<script setup lang="ts">
import { ref } from 'vue';
import child from './child.vue';
const counter = ref(0);
</script>

子组件代码

<template></template>
<script setup lang="ts">
import { onMounted } from 'vue';
const counter = defineModel<number>('counter');
onMounted(() => {
  counter.value++; // 预期值应为1
  console.log(counter.value); // 实际打印0
});
</script>

原因分析

这是预期行为,核心原因是Vue3中defineModel的状态更新是异步的:

  • defineModel本质封装了父子组件间的双向绑定逻辑,当修改子组件中counter.value时,Vue不会立即同步更新父组件的绑定值,也不会立刻刷新子组件内ref的当前值——这个同步过程需要等待组件更新周期触发。
  • 在onMounted钩子中修改值后立即打印,此时组件更新还未执行,所以输出的仍然是修改前的初始值。
  • 如果要获取更新后的正确值,需要通过nextTick等待组件更新完成后再打印:
<script setup lang="ts">
import { onMounted, nextTick } from 'vue';
const counter = defineModel<number>('counter');
onMounted(async () => {
  counter.value++;
  await nextTick();
  console.log(counter.value); // 此时会输出1
});
</script>

内容的提问来源于stack exchange,提问作者Chin. Udara

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 16:22:44