# express-lego **Repository Path**: DhjOring/express-lego ## Basic Information - **Project Name**: express-lego - **Description**: 替换egg-lego - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 1 - **Created**: 2024-10-08 - **Last Updated**: 2025-03-22 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ## SSR后端实现方案 前提: 数据结构要按照规定的数据结构来 1.在数据库中查询对应要渲染的数据 2.在后端中可以使用vue中的createSSRApp来创建一个vue实例,写法可以是选项式或者组合式,可以通过v-for进行动态渲染组件 3.通过renderSsrToString编译成字符串,最后将字符串放入对应的页面模板返回给前端即可 ```javascript //ssr渲染页面 async ssrRenderPage(req, res) { const { idAndUuid } = req.params; const result = splitIdAndUuid(idAndUuid); try { const { desc, title, html, bodyStyle } = await renderPageService(result); console.log(html, "contorller"); return res.render("ssr-template.nj", { desc, title, html, bodyStyle }); } catch (error) { return helper.errorMessage({ res, error, errCode: "pageRenderError" }); } }, function propsToStyle(props = {}) { const keys = Object.keys(props); const styleArr = keys.map((key) => { const formatKey = key.replace(/[A-Z]/g, (c) => `-${c.toLocaleLowerCase()}`); // fontSize -> font-size const value = props[key]; return `${formatKey}: ${value}`; }); return styleArr.join(";"); } module.exports = { async renderPageService(query) { const { id, uuid } = query; const work = await workModel.findOne({ id, uuid }).lean(); console.log(work); if (!work) { throw new Error("找不到该作品"); } const { title, desc, content } = work; const vueApp = createSSRApp({ data: () => { return { components: (content && content.components) || [], }; }, template: '', }); vueApp.use(LegoComponents); const html = await renderToString(vueApp); const bodyStyle = propsToStyle(content && content.props); return { title, desc, html, bodyStyle, }; }, ```