1

我正在尝试在我的 NuxtJS 应用程序中使用 DOMPurify 包将 HTML 解析为干净且安全的字符串,以便在 UI 中呈现。渲染使用包的页面时,出现以下错误:

dompurify__WEBPACK_IMPORTED_MODULE_1___default.a.sanitize is not a function

关于如何解决这个问题的任何建议?我在此处的代码框中有此代码:https://codesandbox.io/s/reverent-bardeen-kh4wg?file=/pages/index.vue: 0-2868

我已将包导入到我的单个文件组件中,如下所示:

<template>
  ......cut unnecessary code for this example...
        <textarea
          id="title_input"
          v-model.trim="formValues.title"
          class="form-control form-control-lg border-0 fw-bold lh-1 fs-1 mb-3"
          placeholder="New post title here..."
          maxlength="80"
          rows="2"
          minlength="6"
          autocomplete="off"
          required
          aria-describedby="titleHelpBlock"
        ></textarea>
        <textarea
          id="content_input"
          v-model.trim="formValues.content"
          class="form-control border-0 h-100"
          rows="3"
          minlength="30"
          maxlength="1000"
          autocomplete="off"
          placeholder="Write your post here..."
          required
          aria-describedby="contentHelpBlock"
        ></textarea>
      
  .....
</template>

<script>
import { debounce } from "lodash";
import DOMPurify from "dompurify";
import marked from "marked";
export default {
  name: "UploadForm",
  data() {
    return {
      formValues: {
        title: "New post title here...",
        content: "Write your post here...",
      },
    };
  },
  computed: {
    compiledMarkdown() {
      // only need the HTML profile, not SVG andMathML stuff
      const clean = DOMPurify.sanitize(this.formValues.title, {
        USE_PROFILES: { html: true },
      });
      return marked(clean);
    },
  },
  methods: {
    update: debounce(function (e) {
      this.input = e.target.value;
    }, 300),
    updateTitle: debounce(function (e) {
      this.formValues.title = e.target.value;
    }, 300),
    updateContent: debounce(function (e) {
      this.formValues.content = e.target.value;
    }, 300),
  },
};
</script>
4

1 回答 1

0

您不能v-html直接用作指令,因为它可能导致 XSS:https ://vuejs.org/v2/guide/syntax.html#Raw-HTML

因此,您需要清理其中一些用户输入。
为了在 Vue/Nuxt 中实现这一点,我建议使用vue-dompurify-html

要遵循的一些步骤

  • 安装它yarn add vue-dompurify-html
  • 像这样将其导入您的.vue文件中
import Vue from 'vue'
import VueDOMPurifyHTML from 'vue-dompurify-html'
 
Vue.use(VueDOMPurifyHTML)
  • 像这样在您的模板中使用它
<div>
  <div v-dompurify-html="rawHtml"></div>
</div>
于 2021-09-06T12:52:54.043 回答