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 (e.g. 'See REFERENCE') and the REFERENCE word should be turned into an anchor link.
E.g.
<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.
The simplest way to get started with Vue is to grab the development version script for it and add it to the head tag of your HTML file. Then you can start Vue code inside the HTML file inside of script tags. And have the Vue code connect up with an existing element on your HTML page.
Going off number 2, because VueJS filters are meant for text transformations, they can only be used in two places: mustache interpolations (the curly braces in your template) and in v-bind expressions.
add: function(item) { this. items. push(item); //change this line to push item to array instead of replacing it everytime. } Another part which you need to fix is, instead of passing an array of items in add method, pass just the item you want to add.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With