使用 Vue,我想显示一个确认模式,其中显示类似“您确定要删除 '{{itemName}}' 吗?”。
将 Javascript 字符串绑定到嵌入到模板中的变量就足够简单了。
但是,如果我想把itemName
用斜体来强调它,我能找到的唯一方法是使用v-html
,这当然会导致 XSS。
有什么方法可以设置字符串的一部分样式吗?
您可以尝试使用类似的包清理 html https://github.com/punkave/sanitize-html。我将这样做:
Install:
npm install sanitize-html
main.js:
import sanitizeHTML from 'sanitize-html';
Vue.prototype.$sanitize = sanitizeHTML;
你的组件.vue:
<div v-html="$sanitize(itemName)" />
看看README https://github.com/punkave/sanitize-html#readme有关允许的标签和属性的默认选项的更多信息。
编辑相应。备择方案:
sanitize-html
其缺点是大小为 327 KB。但还有更小的封装可供选择:
-
DOM纯化 https://github.com/cure53/DOMPurify (15 KB)
-
js-xss https://github.com/leizongmin/js-xss (28 KB)
EDIT 2:
有一个包vue-dompurify-html https://www.npmjs.com/package/vue-dompurify-html我们现在在我们的项目中使用它。安装后您可以简单地使用
<div v-dompurify-html="itemName" />
奖励:通过使用这个包,你可以覆盖推荐的 eslint 规则vue/无-v-html https://eslint.vuejs.org/rules/no-v-html.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)