nuxt3服务端渲染v-html问题

499 阅读1分钟

原本想着使用vue-dompurify-html防御xss攻击, 使用方法是

<div v-dompurify-html="rawHtml"></div>

但是在nuxt使用服务端渲染会出现内容空白,原来vue底层就限制了,如下issues

github.com/vuejs/core/…

记录解决方案 不使用指令v-html,改为引用isomorphic-dompurify加使用h函数渲染:

import DOMPurify, { type Config } from 'isomorphic-dompurify'
 
const RichText = defineComponent({
  props: {
    html: {
      type: String,
      required: true,
    },
    config: {
      type: Object as PropType<Config>,
      default: (): Config => ({
        ALLOWED_ATTR: ['target', 'href', 'ref', 'class', 'style'],
      }),
    },
  },
  computed: {
    clean() {
      return DOMPurify.sanitize(this.html, this.config)
    },
  },
  render() {
    return h('div', { innerHTML: this.clean })
  },
})

export default RichText