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

设置数据后传props遇Hydration错误,Composition API语法存疑?

客户端渲染虚拟DOM与服务端渲染内容不匹配问题

客户端渲染的虚拟DOM树与服务端渲染内容不匹配

我在Nuxt-bridge(Vue 3 + Composition API + TypeScript)项目中遇到上述 hydration 错误。具体场景是:将product初始化为空对象,在onBeforeMount钩子中为其赋值,再通过v-bind传递给子组件。

我尝试用Options API实现完全相同的逻辑,未出现该错误;但用Composition API写法时错误必现。

我添加了v-if="checkData"来判断product是否为非空对象,本以为能消除错误,但并未起效。不过如果直接传递getExampleProd()的返回值(<ChildComponent1 v-bind="getExampleProd()" />),则不会触发错误。

父组件代码

<template>
  <div>
    <h2>New page</h2>
    <hr />
    <ChildComponent1 v-if="checkData" v-bind="product" />

    <!-- <ChildComponent1 v-bind="getExampleProd()" /> -->    //<-- test - no error

  </div>
</template>

<script setup lang="ts">
import { ProductInterface } from '~/types';

import { computed, onBeforeMount } from 'vue';

let product = ref<any>({});

onBeforeMount(() => {
  product.value = getExampleProd();
});

const getExampleProd = () => {
  const obj: ProductInterface = {
    id: 5,
    name: 'Hello prod',
    characteristics: {
      color: 'grey',
      shape: 'strange',
    },
  };
  return obj;
};
const checkData = computed(() => {
  if (isObjectAndNotEmpty(product.value)) {
    return true;
  } else {
    return false;
  }
});
const isObjectAndNotEmpty = (data: any) => {
  if (
    typeof data === 'object' &&
    data !== null &&
    Object.keys(data).length > 0
  ) {
    return true;
  }
  return false;
};
</script>

子组件代码

<template>
  <div class="comp1">
    <h2>Child component!</h2>
  </div>
</template>

<script setup lang="ts">
import { ProductInterface } from '~/types';

interface IProps {
  id: number;
  name: string;
  characteristics: any;
}
const props = defineProps<IProps>();
</script>

疑问

  • 我的Composition API语法是否存在问题?
  • 该错误为何发生?
  • 如何在为product赋值并传递给子组件的同时避免这个错误?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 08:01:00