How to change users mentioned to a html a tag in a post? (VUE-NODE)

前端 未结 2 1838
忘了有多久
忘了有多久 2021-01-27 06:30

I have a body property that contains text that involves @username1 @username2. I want to change where are nicknames @user1 @user2 etc to router-links, its possible to do it with

相关标签:
2条回答
  • 2021-01-27 06:47

    Use named routes and params for route

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

    Named routes:

    const router = new VueRouter({
      routes: [
       // dynamic segments start with a colon
        { name:'user', path: '/profile/:username', component: User }
      ]
    })
    
    0 讨论(0)
  • 2021-01-27 07:03

    I share the solution in this codepen

    CODE:

    <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>
    
    0 讨论(0)
提交回复
热议问题