我得到错误:
客户端呈现的虚拟DOM树与服务器呈现的内容不匹配
我将产品初始化为空对象,然后在onBeforeMount
处为其分配一些数据。产品由v-bind
传递给子组件。我有一个显示控制台错误的复制品。
更新:我做了同样的例子,但使用了选项API语法而不是组合API,错误没有显示(请参阅复制中的链接(。
那么,我的composition api语法有问题吗?
为什么会出现错误,我如何将一些数据分配给产品,并在没有错误的情况下将其传递下去?
我正在使用Nuxt桥接器(Vue 3与构图APA和打字脚本(
<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;
};
我加了一个";CCD_ 3";条件,以检查产品是否为包含数据的对象。只是想看看这个错误是否会消失,但事实并非如此。
如果我直接传递产品数据,没有错误,请参阅行:
<ChildComponent1 v-bind="getExampleProd()" />
子组件基本上是:
<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>();
如果将数据分配给onBeforeMount
挂钩中的属性,显然会导致水合问题。
我相信onBeforeMount
与Nuxt 2中的created
类似,只是onBeforeMount
只在前端运行,而created
同时在前端和后端运行(因此,将数据分配给created
中的属性不会导致水合问题。
Options API示例之所以有效,是因为它使用了created
挂钩。
我认为Nuxt 2上onBeforeMount
的等价物是:
created() {
// Only run on client: hydration issue
if (process.client) {
this.product = this.getExampleProd();
}
},
下面是一个例子(Nuxt 2的水合问题(。
我的解决方案是使用onMounted
:
onMounted(() => {
product.value = getExampleProd();
})