如何在 Vue 2 或 3 中设置 html 转义数据的样式

how to style html escaped data in Vue 2 or 3

我在 Vue 应用程序中显示了用户生成的数据,因此 html 的默认 Vue 行为 - 转义数据是完美的。除了,现在我希望用户能够搜索该数据,并且我想在搜索结果中突出显示匹配的文本。这意味着我需要将我的 own 样式转义为 not,即使所有 original 数据仍然应该逃脱。

换句话说,我需要在 数据被 html 转义之后应用我的样式 ,例如:

1。用户输入数据:

some original data that has special characters like > and <

2。 Vue html-为了安全显示转义这个:

some original data that has special characters like &gt; and &lt;

3。动态设置搜索结果的样式

例如,如果用户搜索“原始数据”,它将变为:

some <span class="my-highlight-style">original data</span> that has special characters like &gt; and &lt;

注意我的动态样式是如何 html 转义的,即使用户输入是。

我当然可以只使用 v-html 完全绕过 html 转义,但是我失去了 html 转义的所有安全和好处,我不想这样做失去。理想情况下,我想显式调用 Vue 的 html 转义例程,然后 应用我的样式,这样它就不会被转义,然后 最终呈现所有这些都没有转义(因为我已经以编程方式应用了适当的转义)。

Vue 是否提供对其 html 转义例程的编程访问? (而且我不是在谈论完全去除特殊字符的 $sanitize,我想像普通 Vue 模板一样保留它们)。我当然可以编写自己的转义例程,只是想知道我是否可以利用 Vue 的代替。

Vue 使用浏览器的 API 来编码 HTML 内容,如此处所述:https://vuejs.org/v2/guide/security.html#HTML-content.

所以,像这样的东西应该为您提供与 Vue 一样的保护,以防止原始用户输入。在计算出的 属性 中,我们通过 p 元素传递用户数据以对其进行编码。然后我们在我们自己的 highlight 计算的 属性 之上链接,我们可以在其中注入我们自己的 HTML,然后用 v-html.

显示
<template>
  <div id="app">
    <div><label>Raw text:<br /><textarea v-model="text" cols="50" rows="10" /></label></div>
    <div><label>Search for: <input type="text" v-model="search" /></label></div>
    <p><label>v-html: <span v-html="text" /></label></p>
    <p><label>Highlighted: <span v-html="highlight" /></label></p>
  </div>
</template>

<script>

export default {
  data() { 
    return {
      text: "some original data that has special characters like > and <",
      search: "original data"
    }
  },
  computed: {
    highlight() {
      const html = this.safeHtml;
      return html.replace(this.search, "<span class='my-highlight-style'>$&</span>");
    },
    safeHtml() { 
      var p = document.createElement("p");
      p.textContent = this.text;
      return p.innerHTML;
    }
  }
}
</script>

<style>
.my-highlight-style {
  background: orange;
  padding: 5px;
}
</style>