在vue中解析字符串html

在vue中解析字符串html

但是不能使用v-html,因为使用v-html绑定的事件无效

有什么方法可以解析字符串html并事件有效的方法吗

参考自 chatGPT:
可以使用Vue的动态组件来实现解析字符串HTML并使事件有效。
首先,将字符串HTML转换为Vue组件,可以使用Vue的compile函数来实现:

import Vue from 'vue'
function compileTemplate(html) {
  return Vue.compile(`<div>${html}</div>`)
}

然后,将编译后的Vue组件渲染到动态组件中:

<template>
  <div>
    <component :is="renderedComponent" @click="handleClick"></component>
  </div>
</template>
<script>
import Vue from 'vue'
export default {
  props: {
    html: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      compiledTemplate: null,
      renderedComponent: null
    }
  },
  mounted() {
    this.compiledTemplate = compileTemplate(this.html)
    this.renderedComponent = this.compiledTemplate ? Vue.extend(this.compiledTemplate).extendOptions : null
  },
  methods: {
    handleClick(event) {
      // handle click event
    }
  }
}
</script>

在上面的代码中,我们将字符串HTML编译为Vue组件,并在组件挂载后将其渲染到动态组件中。同时,我们也可以在动态组件中绑定事件,例如上面的@click事件。
这样就可以解析字符串HTML并使事件有效了,但是需要注意的是,由于字符串HTML可能包含恶意代码,因此需要对输入进行严格的验证和过滤。

DOMPurify 用这个库试试