【问题标题】:How to change users mentioned to a html a tag in a post? (VUE-NODE)如何将帖子中提到的用户更改为 html a 标签? (VUE-节点)
【发布时间】:2020-07-04 19:51:34
【问题描述】:

我有一个 body 属性,其中包含涉及 @username1 @username2 的文本。我想将昵称 @user1 @user2 等在哪里更改为路由器链接,可以使用正则表达式吗?

最终的代码需要是这样的(链接配置文件中没有@)

<router-link :to='/profile/username1'></router-link>

【问题讨论】:

    标签: vue.js vuejs2


    【解决方案1】:

    我在这个codepen分享解决方案

    代码:

    <template>
    <div>
      
      <h3>Original</h3>
      <div id="original" class="box">
        {{body}}
      </div>
      
      <h3>Replaced</h3>
      <div id="replaced" 
            class="box"
            v-html="bodyReplaced"
      ></div>
      
    </div>
    </template>
    
    <script>
    export default {
      data() {
        return {
          body: 'Hi @jrambo and @jwick I am @cincarnato',
          
        };
      },
      computed: {
        bodyReplaced(){
          /* Using string.replace
             1 parameter: regex to match
             2 parameter: a function that return the new text (the funcion receive the string matched by regular expression)
          */
          return this.body.replace(
            /@\w+/g, 
            (user) => '<a href="#" >'+user+'</a>'
          )
        }
      }
    };
    </script>
    
    <style>
      .box{
        border: 1px solid grey;
        padding: 10px;
        margin: 10px;
      }
    </style>
    

    【讨论】:

    • 您好,请检查编辑问题,希望您能帮助我
    【解决方案2】:

    使用命名路由和路由参数

    <router-link :to="{ name: 'user', params: { username: yourUserNameProp }}"></router-link>
    

    命名路线:

    const router = new VueRouter({
      routes: [
       // dynamic segments start with a colon
        { name:'user', path: '/profile/:username', component: User }
      ]
    })
    

    【讨论】:

    • 嗨,问题是如果我更改路由器链接标签的标签没有任何反应,我使用顶部答案中的代码@deffox
    • 我需要在 body 属性中找到 @user 并将其更改为 router-link 以便可点击
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 2012-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多