Vue components / elements in v-html
What you want to do sortof breaks the normal Vue paradigm, but it can be done using Vue.compile
. You'll need to use Vue.compile
to generate the render functions and then manually create a new Vue instance
once your component has been mounted.
Here's an example:
Vue.component('post', {
template: `<div></div>`,
props: { text: String },
mounted() {
let regex = /\B\@([\w\-]+)/gim;
let username = this.text.match(regex)[0];
let linkText = this.text.replace(regex, `<a href="#">${username}</a>`);
let res = Vue.compile(`<p>${linkText}</p>`);
let { render, staticRenderFns } = res;
new Vue({ el: this.$el, render, staticRenderFns })
}
})
new Vue({
el: '#app',
data() {
return { text: `Hi @user1, how are you?` }
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>
<div id="app">
<post :text="text"></post>
</div>