首页 > 解决方案 > 将 VNode 渲染为 html 字符串

问题描述

我正在开发一个 Vue 服务端模板引擎,包的一部分包括一个头部管理系统。

我正在为 Vue 和 SSR 的头部管理开发一个服务器端渲染器,它需要一种将VNodes 渲染为文本的方法。

我的问题: 如何将 VNode(s) 呈现为字符串?例如:

this.$ssrContext.head = renderVNodesToString(this.$slots.head)

示例用例:

master.vue

<template>
    <div id="app">
        <slot name="content"></slot>
    </div>
</template>
<script>
export default {
    created: function(){
        if(this.$isServer){
            var VNodesToRender = this.$slots.head
            this.$ssrContext.head = 'rendered VNode here'
        }
    }
}
</script>

home.vue

<template>
    <master>
        <template slot="content">
            Hello World
        </template>
        <template slot="head">
            <script src="https://unpkg.com/vue/dist/vue.js"></script>
            <title>Hello</title>
        </template>
    </master>
</template>
<script>
import master from "layouts/master.vue"

export default {
    components: {
        master
    }
}
</script>

我的目标是将home.vue' 的head插槽呈现为字符串并将其注入到 中,this.$ssrContext以便可以在服务器端读取和注入

在 中master.vue,我可以毫无问题地访问this.$slots.head,并且它包含正确VNode的 s

字符串的使用位置

{{{ head }}}

const renderer = createBundleRenderer(bundle.server, {
    runInNewContext: false,
    inject: false,
    template: `<!DOCTYPE html>
        <html>
            <head>
                {{{ head }}}
                {{{ renderResourceHints() }}}
                {{{ renderStyles() }}}
            </head>
            <body>
                <!--vue-ssr-outlet-->
                <script>${ bundle.client }</script>
            </body>
       </html>`
})

注意: 这个问题不像:

  1. VueJS 渲染 VNode
  2. 了解 Vnode
  3. 你能在 Vue 模板中渲染 VNode 吗?

因为它需要一个字符串输出,它被传递给 SSR

标签: javascriptvue.js

解决方案


推荐阅读