Vue 预渲染闪烁

Vue prerender flickering

我现在有以下解决方案:

<template>
    <section id="prod-main">
        <prod-preview v-for="prod in products" :id="prod.id" :key="prod.id"/>
    </section>
</template>

export default {
...
    computed: {
        products: function () {
            return this.$store.getters['products/getPreview']
        }
    }
...
}

Vuex 商店将在我的后端延迟一段时间后接收信息。所以一开始它会是空的。现在我想使用 vue spa prerender,这里我看到闪烁。
据我了解,它的工作方式如下:
1. 浏览器加载 HTML 产品
2. 执行js把products替换成nothing,因为store是空的
3. 延迟一段时间后再次显示后端信息。

我该如何解决?我应该为索引保留预渲染,我不能对后端回复进行硬编码。

我不知道我是否理解你的问题,但你是否尝试添加一个 v-if 以避免闪烁:

<template>
    <section id="prod-main">
        <prod-preview
            v-if="products.length > 0" 
            v-for="prod in products" 
            :id="prod.id" 
            :key="prod.id"/>
    </section>
</template>

您可以使用设置 captureAfterTime 等待异步调用完成,然后再保存页面的 html。

其他设置可用:

    // NOTE: Unless you are relying on asynchronously rendered content,
    // such as after an Ajax request, none of these options should be
    // necessary. All synchronous scripts are already executed before
    // capturing the page content.

    // Wait until a specific event is fired on the document.
    captureAfterDocumentEvent: 'custom-post-render-event',
    // This is how you would trigger this example event:
    // document.dispatchEvent(new Event('custom-post-render-event'))

    // Wait until a specific element is detected with
    // document.querySelector.
    captureAfterElementExists: '#content',

    // Wait until a number of milliseconds has passed after scripts
    // have been executed. It's important to note that this may
    // produce unreliable results when relying on network
    // communication or other operations with highly variable timing.
    captureAfterTime: 5000,

另一个问题可能与预渲染的 HTMl 如何水合有关,我已经在 github 上打开了一个问题,但他们仍然没有解决它(并且不愿意? ) https://github.com/chrisvfritz/prerender-spa-plugin/issues/131

解决方案是在预渲染的html中添加data-server-rendered="true"到你的vuejs父节点,像这样:
<div id="root" data-server-rendered="true">...

您可以使用选项 postProcessHtml 来执行此操作。