【问题标题】:Render html from string vuejs从字符串 vuejs 渲染 html
【发布时间】:2021-01-30 16:27:58
【问题描述】:

我正在努力解决一个问题,我想创建一个聊天应用程序,并且用户能够使用 @ 相互标记。例如,user1 输入聊天输入 'hi @user2',输出应该看起来一样,但是 '@user2' 是一个链接而不是简单的文本,我想怎么做,但问题是,如果用户输入例如html标签,它被呈现为html。

HTML:

<span v-html="chatFormat(chat.text)"></span>

VUE:

chatFormat(text) {
  var words = text.split(" ");
  var newStr = '';
  words.forEach(function (word) {
  if (word.includes('@') >= 1) {
    if (word.charAt(0) == '@') {
      word = '{{ <a href="/user" class="font-weight-bold" style="text-decoration:none">' + word + '</a> }}';
    }
  }
  newStr = newStr + ' ' + word;
  });
  return newStr;
}

【问题讨论】:

标签: javascript vue.js


【解决方案1】:

好吧,使用 v-html 指令将值呈现为 HTML - 它不会被解析为变量。 您可以更改您的代码并删除{{}},因此输出中只会出现链接。

word = '<a href="/user" class="font-weight-bold" style="text-decoration:none">' + word + '</a>';

但是,请注意,使用 v-html 显示用户输入是有风险的。应首先转义用户输入以消除潜在的有害代码。 (您可以按照 Michal Levý 的建议查看Sanitizing user input before adding it to the DOM in Javascript

我还建议使用arrow functionstemplate literals

chatFormat(text) {
  // using let instead of var for declaring variables in the local scope
  let safeText= this.sanitizeHTML(text), // for security reasons
      words = safeText.split(" "),
      newStr = '';

  words.forEach(word => { // arrow function
    if (word.includes('@') >= 1) {
      if (word.charAt(0) == '@') {
        word = `<a href="/user" class="font-weight-bold" style="text-decoration:none">${word}</a>`; // template literal
      }
    }
    newStr = newStr + ' ' + word;
  });

  return newStr;
},

// This should be a secure sanitization method from some library
sanitizeHTML(string) {
  return string
},

【讨论】:

    【解决方案2】:

    一个已经讨论过多次的主题。

    在 Vuejs.org 中:https://vuejs.org/v2/api/#v-html

    在 stackoverflow.com 中:(众多之一)Rendering html tags in Vue.js

    【讨论】:

      猜你喜欢
      • 2020-05-04
      • 2017-03-21
      • 2018-08-30
      • 2019-11-26
      • 2014-08-29
      • 2012-08-20
      • 2019-07-19
      • 2017-09-05
      • 2011-02-12
      相关资源
      最近更新 更多