【问题标题】:Adding html in Vue.js using data filters?使用数据过滤器在 Vue.js 中添加 html?
【发布时间】:2018-09-25 21:47:36
【问题描述】:

我正在尝试使用 Vue.js 中的过滤器功能在字符串中添加 html 标签,文档表明这应该是可行的,但我无处可去。关键是数据应该只是一个带入 html 的字符串,在安装之前,过滤器应该在数据中搜索关键字(例如“查看参考”),并且参考字应该变成锚链接。

例如

 

{{字符串 |过滤函数}}

不要说:

 

带有链接的文本字符串

它应该通过管道输出字符串,但插入一个节点。

 

带有链接的文本字符串

Vue 文档表明 javascript 组件组合是可能的,但到目前为止测试进展不佳。

【问题讨论】:

  • How to make links clickable in a chat 的可能重复项,虽然这不使用过滤器,但它显示了如何以您想要的方式使链接可点击
  • 分享您的代码的现场演示?
  • {{ String | filterFunction }} 中的字符串是由一个对象组成还是只是一个字符串?
  • 为什么不使用 v-html 指令? vuejs.org/v2/guide/syntax.html#Raw-HTML
  • 我希望有一种过滤方法,但我想这与功能性 Vue 组件中的渲染相比不合适 - 谢谢。

标签: javascript html filter vue.js


【解决方案1】:

过滤器仅替换为文本。由于您试图在 HTML 中转换纯文本,因此您必须求助于 v-html 或等效的。在下面的演示中检查您的选项。

function _linkify(text) {
  return text.replace(/(https?:\/\/[^\s]+)/g, '<a href="$1">$1</a>');
}

Vue.filter('linkify', function (value) {
    return _linkify(value)
})

Vue.component('linkify', {
  props: ['msg'],
  template: '<span v-html="linkifiedMsg"></span>',
  computed: {
  	linkifiedMsg() { return _linkify(this.msg); }
  }
});

Vue.component('linkify-slot', {
  render: function (h) {
    let html = _linkify(this.$slots.default[0].text);
    return h('span',{domProps:{"innerHTML": html}})
  }
});

new Vue({
  el: '#app',
  data: {
    message: 'The text string with a http://example.com'
  },
  methods: {
    linkifyMethod(text) {
      return _linkify(text); // simply delegating to the global function
    }
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>Doesn't work: {{ message | linkify }}</p>
  
  <p v-html="$options.filters.linkify(message)"></p>
  
  <p :inner-html.prop="message | linkify"></p>
  
  <p v-html="linkifyMethod(message)"></p>
  
  <p><linkify :msg="message"></linkify></p>
  
  <p><linkify-slot>{{ message }}</linkify-slot></p>
</div>

【讨论】:

  • 第三个选项满足了我的需求&lt;p :inner-html.prop="message | linkify"&gt;&lt;/p&gt;。谢谢!
  • 这里也一样——第三个选项不费吹灰之力——谢谢;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-07
  • 2016-06-17
  • 2013-04-04
  • 2017-03-14
  • 2021-07-05
相关资源
最近更新 更多