Vue - 确认消息中的样式用户输入(允许特定的 html 标签) [英] Vue - style user input in confirm message (allow specific html tags)
问题描述
使用 Vue,我想显示一个确认模式,上面写着您确定要删除 '{{itemName}}' 吗?".
通过将 Javascript 字符串绑定到嵌入在模板中的变量,这很容易.
但是,如果我想将 itemName
放在斜体中以强调它,我能找到的唯一方法是使用 v-html
,这当然会打开它高达 XSS.
有没有办法对字符串的一部分进行样式设置?
你可以尝试使用像 消毒-html.这是我的做法:
安装:
npm install sanitize-html
main.js:
从 'sanitize-html' 导入 sanitizeHTML;Vue.prototype.$sanitize = sanitizeHTML;
YourComponent.vue:
查看自述文件,了解有关允许标签默认选项的更多信息和属性.
分别编辑替代方案:
sanitize-html
有一个 327 KB 重量的缺点.但是有更小的包可用:
编辑 2:
我们正在使用一个包 vue-dompuritfy-html现在在我们的项目中.安装后你可以简单地使用
奖励:使用这个包,你涵盖了推荐的 eslint 规则 vue/no-v-html
Using Vue, I want to show a confirmation modal that says something like "Are you sure you want to delete '{{itemName}}'?".
That's easy enough with a Javascript string being bound to a variable which is embedded in the template.
However, if I want to put the itemName
in italics to emphasis it, the only way I can find is to use v-html
, which of course would open it up to XSS.
Is there any way to style part of the string?
解决方案 You can try to use a package like sanitize-html. Here is how I would do it:
Install:
npm install sanitize-html
main.js:
import sanitizeHTML from 'sanitize-html';
Vue.prototype.$sanitize = sanitizeHTML;
YourComponent.vue:
<div v-html="$sanitize(itemName)" />
Have a look at the README for more information about default options for allowed tags and attributes.
EDIT resp. Alternatives:
sanitize-html
has a drawback of a 327 KB weight. But there are smaller packages available:
EDIT 2:
There is a package vue-dompuritfy-html which we are using in our projects now. After installing you can simply use
<div v-dompurify-html="itemName" />
Bonus: with the use of this package you cover the recommended eslint rule vue/no-v-html
这篇关于Vue - 确认消息中的样式用户输入(允许特定的 html 标签)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文