确认消息中的Vue风格用户输入(允许使用特定的html标签)

时间:2019-03-18 16:14:23

标签: vue.js vuejs2 xss

使用Vue,我想显示一个确认模式,内容为“您确定要删除'{{itemName}}'吗?”。

通过将Javascript字符串绑定到模板中嵌入的变量,这很容易。

但是,如果我想用斜体字来强调itemName,我唯一能找到的方法就是使用v-html,这当然会使其适用于XSS。

有什么方法可以设置字符串的一部分样式?

3 个答案:

答案 0 :(得分:4)

您可以尝试使用sanitize-html之类的软件包。这是我的方法:

安装:

npm install sanitize-html

main.js:

import sanitizeHTML from 'sanitize-html';
Vue.prototype.$sanitize = sanitizeHTML;

YourComponent.vue:

<div v-html="$sanitize(itemName)" />

请查看README,以获取有关允许的标签和属性的默认选项的更多信息。

编辑响应。替代方法:

sanitize-html的缺点是327 KB。但是有一些较小的软件包可用:

答案 1 :(得分:3)

这样定义模态:

模板

<div class="modal">
  <slot></slot>
  <button @click="$emit(true)">Yes</button>
  <button @click="$emit(false)">No</button>
</div>

样式

.modal > em {
  /* apply anything you want here */
}

然后在同伴中使用模态:

模板

<template>
  ...
    <modal>Are you sure you want to delete <em>{{itemName}}</em>?</modal>
  ...
</template>

答案 2 :(得分:0)

我看过其他答案,我推荐拉沙德·萨利赫(Rashad Saleh)的答案,一个带有槽的模型,您可以使用v-if显示模型,并使用v-*指令切换内容,那么您不需要为每种情况创建每个模板

我发布了另一个答案,它的使用方式完全不同,sweet-alert不会与您的诉求冲突,并且完全以JavaScript方式使用。

var something = document.getElementById('xss').value

var toshow = encodeURIComponent(something)

Swal.fire({
  title: 'Are you sure?',
  html: "You won't be able to revert <b><em>" + toshow + "</em></b>!",
  type: 'warning',
  showCancelButton: true,
  confirmButtonColor: '#3085d6',
  cancelButtonColor: '#d33',
  confirmButtonText: 'Yes, delete it!'
}).then((result) => {
  if (result.value) {
    Swal.fire(
      'Deleted!',
      'Your file has been deleted.',
      'success'
    )
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.33.1/sweetalert2.all.min.js"></script>

<input id="xss" value="<script>alert('xss')</script>">

您可能需要自定义甜蜜警报的样式,尽管它已经足够了,有关更多信息,请参见https://sweetalert2.github.io/