【问题标题】:How to render only anchor tags in v-html element and avoid others and show them as string如何仅在 v-html 元素中呈现锚标记并避免其他标记并将它们显示为字符串
【发布时间】:2021-05-03 11:42:28
【问题描述】:

我只想在我的 vue 项目(在 v-html 中)属性中呈现锚标记并将其他 html 标记呈现为字符串。

类似于 Linkedin 的东西。 example

我尝试使用 linkifyjs 库,但不知道如何仅在 dom 上显示链接。

【问题讨论】:

  • 你研究过 Vue-Linkify 吗?
  • @Ali 这个库是易受攻击的,它允许你在应用程序中注入任何 iframe 或可疑脚本。

标签: javascript vue.js vuejs2 vue-component


【解决方案1】:

创建一个computed property(命名为myContent)绑定到元素的v-html:

<div v-html="myContent"></div>

myContent 应该:

  1. 用&amp;lt; 替换所有&lt; 字符,这会转义HTML 标记。

  2. 使用带有正则表达式的replacer function,将href 和src 属性的所有值替换为锚标记。

  3. 在结果上调用 linkifyjs 以在标记中创建任何独立 URL 的链接。

import linkifyHtml from 'linkifyjs/html'

export default {
  computed: {
    myContent() {
      const markup = this.html
        .replace(/</g, '&lt;')
        .replace(/((?:href|src)=['"])(.*?)(['"])/g, (matched, prefix, href, suffix) => {
          return `${prefix}<a href="${href}" target="_blank">${href}</a>${suffix}`
        })

      return linkifyHtml(markup, { target: { url: "_blank" } })
    },
  },
}

demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多