记录:vue组件转为HTML字符串

494 阅读1分钟

image.png 今天做了个需求,要求是在a项目中写个通用组件,但是以html字符串的方式传到b项目去渲染

      b.render("<div> <span></span></div>")  大概就是调用b项目的方法传入html字符串

第一种方式:vue的createApp

//test.vue 
<template>
    <div
      :style="{ display: 'flex', flexDirection: 'column', backgroundColor: 'pink' }"
    >
      <div v-for="(item, index) in list" :key="index" >
        <div
          :style="{
            width: '15px',
            height: '15px',
            background: ' #08e2ea',
            borderRadius: '50%',
            boxShadow: ' 0px 0px 5px #08e2ea',
            filter: 'blur(0.5px)'
          }"
        ></div>
        <div>范围:</div>
        <div>365m-378.138m</div>
      </div>
     </div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const list = ref([{}, {}, {}])
</script>
<style scoped lang="less">
</style>
//other.vue
import { h, createApp } from 'vue'
import Test from '@/components/xxx/test.vue'
import { render } from 'b'  //b项目暴露的方法,b在npm上,install到了a项目
const app = createApp(Test)
const root = document.createElement('div')
document.body.appendChild(root)
app.mount(root)
const html = root.innerHTML
console.log(html)  //打印结果如下图
render(html)
app.unmount(app)//获取完销毁

image.png

缺点:只能写成内联样式,而且css中有本地背景图的话也加载不出来

第二种方式:vue的SSR

import panelCard4 from 'big-screen-components/src/components/content/panel/panelCard4/panelCard4.vue'
import { renderToString } from 'vue/server-renderer'
import { h } from 'vue'
const app = h(panelCard4, {传入的参数})
renderToString(app).then(async (html) => {console.log(html)})

非常好用,正常写组件传入即可,css,js暂时没发现有什么问题