如何将Vue组件作为短代码加载并替换CMS返回HTML中的对应标记
Vue动态渲染CMS内容中占位符组件的解决方案
针对你需要将CMS返回HTML中的占位符替换为Vue组件的需求,有两种成熟的实现方案:
方案一:字符串分割 + 分段渲染(轻量场景首选)
该方案不需要依赖模板编译能力,安全性更高,适合占位符类型少的场景:
- 先将CMS返回的HTML字符串按占位符分割为静态HTML段和占位符标识的列表
- 遍历列表,静态内容用
v-html渲染,匹配到占位符时渲染对应组件
示例代码(Vue3):
<script setup> import { ref } from 'vue' import ProjectList from './ProjectList.vue' // CMS返回的原始HTML内容 const rawCmsHtml = ref('<div><p>Lorem Ipsum</p>[ProjectList]<p>Some more content</p></div>') // 组件映射表,仅允许列表内的组件被渲染 const componentMap = { ProjectList } // 解析内容拆分为分段数据 const parsedContent = rawCmsHtml.value.split(/(\[ProjectList\])/).map(part => { if (part === '[ProjectList]') return { type: 'component', key: 'ProjectList' } return { type: 'html', content: part } }) </script> <template> <div class="cms-render-box"> <template v-for="(item, idx) in parsedContent" :key="idx"> <span v-if="item.type === 'html'" v-html="item.content" /> <component v-else :is="componentMap[item.key]" /> </template> </div> </template>
方案二:Compile API编译渲染(适合复杂多占位符场景)
如果占位符数量多、甚至带参数(比如[ArticleList category="dev"]),可以用Vue的编译能力直接将处理后的内容转为可执行的组件:
注意:该方案需要你在项目配置中开启runtimeCompiler: true,且确保CMS返回的内容是可信的,避免XSS风险
示例代码(Vue3):
<script setup> import { ref, compile } from 'vue' import ProjectList from './ProjectList.vue' import ArticleList from './ArticleList.vue' const rawCmsHtml = ref('<div><p>Lorem Ipsum</p>[ProjectList]<p>Some more content</p></div>') // 将所有占位符替换为Vue组件标签 const processedHtml = rawCmsHtml.value .replace('[ProjectList]', '<ProjectList />') .replace(/\[ArticleList (.*?)\]/g, '<ArticleList $1 />') // 编译为渲染函数 const DynamicCmsComponent = { components: { ProjectList, ArticleList }, render: compile(processedHtml) } </script> <template> <DynamicCmsComponent /> </template>
如果使用Vue2,替换为Vue.compileAPI即可,使用逻辑一致。
内容的提问来源于stack exchange,提问作者HBV
相关产品推荐
相关产品推荐

