Vuejs:根据 eslint 规则对 html 数据进行 V-HTML 数据绑定

问题描述 投票:0回答:5

我正在使用以下方法绑定html并显示在我的页面中。它工作完美,但是我收到来自 eslint 的警告,“v-html”指令可能导致 XSS 攻击。eslint(vue/no-v-html)

  <button
        id="foreignerBtn"
        class="tabButton"
        @click="foreignerClick"
        v-html="textContent2"
      ></button>

然后我按照以下方法更改它。但我无法渲染 html 标签。

 <button
            id="foreignerBtn"
            class="tabButton"
            @click="foreignerClick"
          >{{ textContent2 }}</button>
javascript html vue.js data-binding eslint
5个回答
34
投票

正如 Decade Moon 提到的,如果传递给 v-html 的内容是经过净化的 HTML,则可以禁用该规则。

https://eslint.vuejs.org/rules/no-v-html.html

通过将 html 包裹起来来禁用规则

<!-- eslint-disable vue/no-v-html -->
<button
        id="foreignerBtn"
        class="tabButton"
        @click="foreignerClick"
        v-html="textContent2"
      ></button>
<!--eslint-enable-->

8
投票

如其他答案中所述,您可以禁用警告,但一个好的做法是确保正确禁用该规则。

为此,您可以使用 dompurify 来解析您提供给浏览器的 HTML,删除任何恶意部分并安全地显示它。

问题仍然存在,但你可以使用 RisXSS,这是一个 ESLint 插件,它会警告使用

v-html
if 你之前没有清理它(从某种意义上说,这是
vue/no-v-html
的改进版本) ESLint 规则)。

为此,请安装

dompurify
eslint-plugin-risxss

npm install dompurify eslint-plugin-risxss

risxss
添加到您的 ESLint 插件,然后使用 DOMPurify:

<template>
    <button
        id="foreignerBtn"
        class="tabButton"
        @click="foreignerClick"
        v-html="sanitizedTextContent2"
        <!-- no warning, good to go -->
    ></button>
    <button
        id="foreignerBtn"
        class="tabButton"
        @click="foreignerClick"
        v-html="textContent2"
        <!-- warning here -->
    ></button>
</template>
<script>
import DOMPurify from 'dompurify';

export default {
    data () {
    return {
        sanitizedTextContent2: DOMPurify.sanitize(textContent2)
    }
    }
}
</script>

免责声明:我是 RisXSS 插件的贡献者。


3
投票

按照 clementescolano 的 answer,我使用 自定义指令想出了以下解决方案:

在你的

main.js
(或者你定义vue实例的任何地方),添加:

import DOMPurify from "dompurify";

// ...

Vue.directive("sane-html", (el, binding) => {
  el.innerHTML = DOMPurify.sanitize(binding.value);
});

现在,无论您在何处使用指令

v-html
,请改用
v-sane-html

注:请参阅 here 了解 vue2 自定义指令


0
投票

您可以将代码包装在

<!-- eslint-disable -->
<button
  id="foreignerBtn"
  class="tabButton"
  @click="foreignerClick"
  v-html="textContent2"
></button>
<!-- eslint-enable -->

它将隐藏所有 eslint 警告,包括 v-html


0
投票

我想禁用我的整个项目,所以我在“eslintConfig”的“规则”中添加了这一行

"eslintConfig": {
   ...
   "rules": {
     ...
     "vue/no-v-html": "disable"
   }
© www.soinside.com 2019 - 2024. All rights reserved.