【问题标题】:Vue components / elements in v-htmlv-html 中的 Vue 组件/元素
【发布时间】:2018-03-16 23:52:23
【问题描述】:

我有一个 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

但是当我这样使用它时:

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

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

如何解决这个问题?谢谢

【问题讨论】:

    标签: javascript vue.js vuejs2


    【解决方案1】:

    你想做的事情有点打破了正常的 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>

    【讨论】:

      【解决方案2】:

      你不需要使用v-html

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

      【讨论】:

        猜你喜欢
        • 2023-03-23
        • 2019-10-28
        • 1970-01-01
        • 1970-01-01
        • 2018-12-03
        • 2017-11-26
        • 2019-05-12
        • 1970-01-01
        • 2020-12-22
        相关资源
        最近更新 更多