vue2.6.10+vite2开启template模板动态编译的过程

在从vue-cli迁移到vite2的时候,之前在代码中使用的模板编译遇到了问题:

我在项目中会根据后台返回的内容动态渲染,如果返回内容中有<el-image>等标签,v-html无法识别非html标签,导致图片渲染失败,因此希望通过模板编译的方式,将字符串传递给template字段,进行渲染。

代码如下:

<!-- 用来渲染元素的组件 -->
<script lang="jsx">
import Vue from 'vue'
export default {
 name: 'renderContent',
 props: {
 html: String,
 elImage: Boolean, // 是否把图片处理成el-image
 },
 data () {
 return {
 }
 },
 components: {
 },
 computed: {
 },
 render(h) {
 let htmlString = this.html || ''
 if(this.elImage === true) {
 // 把res中的updateDesc中的image处理成el-image
 // 匹配img的表达式
 let reg1 = new RegExp(/<img [^>]*src=['"]([^'"]+)[^>]*>/gi);
 if(htmlString) {
 htmlString = htmlString.replace(reg1, function (match, capture) {
 return `<el-image src="${capture}" style="max-width: 100%;" fit="contain" :preview-src-list="['${capture}']"></el-image>`
 });
 }
 }
 // 进行xss过滤
 htmlString = this.$utils.xssFilter(htmlString)
 const com = Vue.extend({
 template: `<div>${htmlString}</div>`
 })
 return h(com, {})
 }
}
</script>

此时会遇到报错:

在vue-cli中,可以通过在vue.config.js中进行配置,解决此问题:

module.exports = {
 ...,
 runtimeCompiler: true,
}

在vite中,我没有找到类似于vue-cli中直接进行配置的方法,经过参考后,发现可以通过以下方法解决:在vite.config.js中进行配置(直接贴我的解决办法):

export default defineConfig({
 resolve: {
 alias: {
 ...,
 "vue": "vue/dist/vue.common.prod.js", 
 },
 },
})

因为vite默认使用的vue是runtime-only的,所以通过声明使用其他版本的vue来解决(具体vue 文件的名称根据版本有差别,我使用的版本是vue2.6.10)

各个版本的大小和功能略有差异,大家选择自己合适的就行。

其他的解决方案:使用web-component 自定义<el-image> 节点等。

参考文章:

Vue 能否实现动态编译template模板?

Vue隐藏技能——运行时渲染

作者:yang1067155909原文地址:https://blog.csdn.net/yang1067155909/article/details/128847187

%s 个评论

要回复文章请先登录注册