我正在开发一个 Vue 服务器端模板引擎,该包的一部分包括一个头管理系统。
我正在为 Vue 开发一个服务器端渲染器,为了让 SSR 的主管管理工作,它需要一种将VNodes 渲染为文本的方法。
我的问题: 如何将 VNode 渲染为字符串?例如:
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>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
我的目标是将home.vue的head插槽渲染为字符串并将其注入到 中this.$ssrContext,以便可以在服务器端读取和注入它
在 中master.vue,我可以this.$slots.head毫无问题地访问,并且它包含正确的VNodes
使用字符串的地方
在{{{ 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>`
})
Run Code Online (Sandbox Code Playgroud)
注意: 这个问题不像:
因为它需要一个字符串输出,该输出被传递到 SSR