V-html中的Vue组件/元素 [英] Vue components / elements in v-html
问题描述
我有一个 post.text
包含用户提交的博客帖子文本的数据很像在Twitter中,用户可以提及其他用户使用sintax 我在这篇文章中标记@ user1
。在渲染帖子时,我想用所有用户的页面链接替换所有 @username
实例。
I have a post.text
data that contains the text of a blog post submitted by the user Much like in Twitter, users can mention other users with the sintax I am tagging @user1 in this post
. When rendering the post, I want to replace all the @username
instances with links to the page of the mentioned user.
使用正则表达式匹配/替换我可以轻松地将提到的 @username
转换为类似的东西(我正在使用vue-router):
With a regex match / replace I can easily transform the mentioned @username
into something like (I'm using 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不会重新处理 html来绑定自己的标签。
vue doesn't reprocess the html to bind its own tags.
如何解决这个问题?谢谢
How to solve this problem? Thanks
推荐答案
你要做什么sortof打破正常的Vue范例,但可以使用 Vue.compile
。您需要使用 Vue.compile
生成渲染函数,然后在装入组件后手动创建一个新的Vue实例
。
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.
以下是一个例子:
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中的Vue组件/元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!