Vue components / elements in v-html

I have post.text data containing the text of a blog post submitted by a user. Like Twitter, users can specify other users using sintax I am tagging @user1 in this post . When rendering a message, I want to replace all instances of @username links to the specified user’s page.

With regex match / replace, I can easily convert the mentioned @username into something like (I use vue-router):

 I am tagging <router-link :to="{name: 'user', params: {userId: post.userId}}">{{ dPost.user_name }}</router-link> in this post 

But when I use it like this:

 <p v-html="preparedText"></p> 

vue does not process html to bind its own tags.

How to solve this problem? Thanks

+6
source share
2 answers

What you want to do sortof violates the normal Vue paradigm, but it can be done using Vue.compile . You will need to use Vue.compile to create the rendering functions, and then manually create a new instance of Vue after installing the component.

Here is 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> 
+5
source

You do not need to use v-html .

To dynamically render your components, simply use :is="your component name" .

0
source

Source: https://habr.com/ru/post/1273242/


All Articles