pis*_*hio 6 javascript vue.js vuejs2
我有一个post.text数据,其中包含用户提交的博客文章的文本很像在Twitter,用户可以提到其他用户使用sintax I am tagging @user1 in this post.在渲染帖子时,我想@username用指向所述用户页面的链接替换所有实例.
使用正则表达式匹配/替换,我可以轻松地将提到的内容@username转换为(我正在使用vue-router):
I am tagging <router-link :to="{name: 'user', params: {userId: post.userId}}">{{ dPost.user_name }}</router-link> in this post
Run Code Online (Sandbox Code Playgroud)
但是当我像这样使用它时:
<p v-html="preparedText"></p>
Run Code Online (Sandbox Code Playgroud)
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?` }
}
})Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script>
<div id="app">
<post :text="text"></post>
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1486 次 |
| 最近记录: |