首页 > 解决方案 > v-for throw 渲染的来自 AsyncData/fetch 的数组列表:客户端渲染的虚拟 DOM 树与服务器渲染的不匹配

问题描述

我正在为我的应用程序使用 Nuxt.js。在我的一个页面中,我使用AsyncData从我的 Api 异步获取一组数据对象,我使用v-for. 当我使用nuxt-link<a href=".."></a> . v-for只要我包含nuxt-link或包含<a href=".."></a>在我的v-for中,我就会收到以下错误:

The client-side rendered virtual DOM tree is not matching server-rendered content. 
This is likely caused by incorrect HTML markup, for example nesting block-level elements inside <p>, or missing <tbody>. 
Bailing hydration and performing full client-side render.

我尝试完成的一个基本示例:

<template>
<div>
  <div
    class="place-card"
    :key="place._id"
    v-for="place in places"
  >
    <nuxt-link
      :to="{
        name: 'places-title',
        params: { title: place.title }
      }"
    >
      <PlaceCard :place="place" />
    </nuxt-link>
  </div>
</div>
</template>

<script>
export default {
  asyncData() {
    // Some preprocessing
    return { places: [{...}, ..., {...}] }
  }
}
</script>

v-for当我将整个div 包装到@Mohsens 答案以及此处<client-only>...</client-only>描述的此处时,我能够使其正常工作。

不幸的是,<client-only></client-only>它阻止了异步数据的服务器端呈现。但是,由于 SEO,我确实需要在服务器端预取我的数据。

有谁知道这个问题的另一种解决方案?

编辑 12.10.2020 扩展日志

组件原代码PlaceCard

<template>
  <div class="bg-white rounded overflow-hidden shadow-lg">
    <img :src="place.images[0]" :alt="place.title" class="w-full h-40" />
    <div class="px-6 pt-4">
      <div class="font-bold text-base">{{ place.title }}</div>
    </div>
    <div class="px-6 pb-4">
      <nuxt-link :to="'/'"
        >#{{ place.placeType.split(' ').join('') }}</nuxt-link
      >
      <nuxt-link :to="'/'">#{{ place.address.country }}</nuxt-link>
      <nuxt-link :to="'/'" v-if="place.vegan">#vegan</nuxt-link>
      <nuxt-link :to="'/'" v-else>#not-vegan</nuxt-link>
      <nuxt-link :to="'/'" v-if="place.vegetarian">#vegetarian</nuxt-link>
      <nuxt-link :to="'/'" v-else>#not-vegetarian</nuxt-link>
    </div>
    <div class="author flex items-center py-3 px-6">
      <div class="user-logo">
        <img
          class="w-8 h-8 object-cover rounded-full mr-2 shadow"
          :src="place.creator.photoURL"
          :alt="place.creator.displayName"
        />
      </div>
      <div class="block text-xs">
        Added by<a href="#" class="ml-1">{{
          place.creator.displayName.split(' ').join('')
        }}</a>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    place: {
      type: Object,
      default: null
    }
  }
}
</script>

标签: javascriptvue.jsvuejs2nuxt.js

解决方案


我想到了。根据herehere,我有一个嵌套链接,一个在我的v-fordiv 内,另一个在我的PlaceCard组件内,这是不允许的。


推荐阅读