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

我正在使用以下方法绑定 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>


月关宝盒
浏览 171回答 5
5回答

HUH函数

如果传递给 v-html 的内容是经过净化的 HTML,则可以禁用该规则。通过将 html 包裹起来来禁用该规则<!-- eslint-disable vue/no-v-html --><button        id="foreignerBtn"        class="tabButton"        @click="foreignerClick"        v-html="textContent2"      ></button><!--eslint-enable-->

慕森卡

正如另一个答案中所述,您可以禁用警告,但一个好的做法是确保正确禁用该规则。为此,您可以使用dompurify来解析您提供给浏览器的 HTML,删除任何恶意部分并安全地显示它。问题仍然存在,但你可以使用RisXSS ,它是一个 ESLint 插件,v-html 如果你之前没有清理它,它会警告用户(从某种意义上说,这是vue/no-v-htmlESLint 规则的改进版本)。为此,请安装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>

跃然一笑

在你的main.js(或者你定义 vue 实例的任何地方),添加:import DOMPurify from "dompurify";// ...Vue.directive("sane-html", (el, binding) => {  el.innerHTML = DOMPurify.sanitize(binding.value);});现在,无论您在何处使用该指令v-html,请v-sane-html改为使用。

牛魔王的故事

我想禁用整个项目,所以我在“eslintConfig”的“rules”中添加了这一行"eslintConfig": {&nbsp; &nbsp;...&nbsp; &nbsp;"rules": {&nbsp; &nbsp; &nbsp;...&nbsp; &nbsp; &nbsp;"vue/no-v-text-v-html-on-component": "warn"&nbsp; &nbsp;}

函数式编程

您可以将代码包装在<!-- eslint-disable --><button&nbsp; id="foreignerBtn"&nbsp; class="tabButton"&nbsp; @click="foreignerClick"&nbsp; v-html="textContent2"></button><!-- eslint-enable -->它将隐藏所有 eslint 警告,包括 v-html
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5