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

Nuxt3 hydration children mismatch问题求助:v-for渲染异常

解决Hydration Children Mismatch警告方案

1. 初始化Pinia状态为空数组

确保categories在Pinia store的state中初始化为空数组,避免服务端渲染时因undefined导致DOM结构差异:

// Pinia store
export const useCatalog = defineStore('catalog', {
  state: () => ({
    categories: [] as categoryType[] // 初始化为空数组
  }),
  // ...其他actions、getters
})

2. 替换Pinia中的useFetch为$fetch

useFetch是Nuxt的组合式函数,在Pinia action中使用可能引发服务端/客户端上下文不一致问题,改用Nuxt内置的$fetch发起请求:

// Pinia action修改
actions: {
  async getCategories() {
    interface responseType {
      data: categoryType[],
      meta: []
    }

    const mainStore = useMain()
    mainStore.$state.isLoading = true;
    try {
      const response = await $fetch<responseType>(`${useRuntimeConfig().public.strapi.url}/api/categories`, {
        method: "GET",
        headers: {
          "Content-Type": "application/json",
        },
      })
      this.categories = response.data
    } catch (error) {
      // 按需添加错误处理逻辑
    } finally {
      mainStore.$state.isLoading = false;
    }
  }
}

3. 用useAsyncData确保服务端预取数据

在组件中使用Nuxt的useAsyncData调用Pinia action,保证服务端渲染时已完成数据获取,让服务端与客户端生成的DOM结构完全一致:

<template>
  <ul class="filter-item-list">
    <li v-for="item in categories" :key="item.id">
      <label class="radio" @click.stop="typeProduct = item.attributes.Title">
        <input type="radio" name="typeProduct" :checked="item.attributes.DefaultCategory">
        <span class="icon"></span>
        <span class="text">{{ item.attributes.Title }}</span>
      </label>
    </li>
  </ul>
</template>

<script setup lang="ts">
import { storeToRefs } from 'pinia'

const catalogStore = useCatalog()
// 触发数据获取,确保服务端预取完成后再渲染
await useAsyncData('categories', () => catalogStore.getCategories())
// 将store中的categories转为响应式ref
const { categories } = storeToRefs(catalogStore)
</script>

4. 验证key的唯一性

确认v-for绑定的:key="item.id"是唯一且稳定的标识符,避免因key重复或不稳定引发DOM渲染差异。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:22:57