简体   繁体   中英

Adding html in Vue.js using data filters?

I am trying to use the Filter feature in Vue.js to add html tags inside a String, the documents suggests this should be somehow feasible but I'm getting nowhere. The point is the data should just a String that's brought into the html and before it's mounted the filter should search the data for key words (eg 'See REFERENCE') and the REFERENCE word should be turned into an anchor link.

Eg

<p>{{String | filterFunction}}</p>

Instead of piping out say:

<p>The text string with a link</p>

It should pipe out the string but with a node insert.

<p>The text string with a <a href="someLink">link</a></p>

The Vue documentation suggests javascript component assemblage is possible but so far the testing has gone poorly.

Filters only replace as text. Since you are trying to transform plain text in HTML, you'll have to resort to v-html or equivalent. Check your options in the demo below.

 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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM