繁体   English   中英

v-html 中的 Vue 组件/元素

[英]Vue components / elements in v-html

我有一个post.text数据,其中包含用户提交的博客文章的文本 就像在 Twitter 中一样,用户可以使用I am tagging @user1 in this post的 sintax 提及其他用户。 呈现帖子时,我想将所有@username实例替换为指向所提及用户页面的链接。

通过正则表达式匹配/替换,我可以轻松地将提到的@username转换为类似的东西(我正在使用 vue-router):

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

但是当我这样使用它时:

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

vue 不会重新处理html 来绑定自己的标签。

如何解决这个问题呢? 谢谢

你想做的事情有点打破了正常的 Vue 范式,但可以使用Vue.compile来完成。 您需要使用Vue.compile来生成渲染函数,然后在安装组件后手动创建一个新的 Vue 实例。

这是一个例子:

 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>

您不需要使用v-html

要动态呈现您的组件,只需使用:is="your component name"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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