簡體   English   中英

如何將提及標簽文本轉換為<router-link> ? (VUEJS)</router-link>

[英]How to convert a mention tag text to a <router-link> ? (VUEJS)

我在數據中有一個 body 屬性

data(){
 return{
  body:'Hello im @username1 and @username2'
 }
}

我想將每個@user 轉換為下面的代碼,用戶可以在其中單擊指向 go 的 url 路徑的鏈接。

<router-link :to="`/${username1}`">@{{username1}}</router-link>

我試過的

<span v-html='bodyReplaced'>
  computed: {
    bodyReplaced(){
      return this.body.replace(
        /@\w+/g, 
        (user) => '<router-link :to="`/${username1}`">@{{username1}}</router-link>'
      )
    }
  }

代碼做了什么:

  1. 將字符串轉換為dom中的router-link,但不在視圖中
  2. 我不知道如何在比賽后替換@,所以我可以在 to="`/${username1} 中使用它

我想你正在尋找類似的東西

<template v-for="part of body.split(/(@\w+)/g)">
  <router-link v-if="part[0] == '@'" :to="`/${part.slice(1)}`">{{part}}</router-link>
  <template v-else>{{part}}</template>
</template>

 new Vue({ el: 'main', data: { body:'Hello im @username1 and @username2' }, router: new VueRouter({ routes: [] }), })
 <main> <template v-for="part of body.split(/(@\w+)/g)"> <router-link v-if="part[0] == '@'":to="`/${part.slice(1)}`">{{part}}</router-link> <template v-else>{{part}}</template> </template> </main> <script src="https://unpkg.com/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>

創建一個名為mention的組件並將用戶名作為prop傳遞,我使用了與@Bergi相同的方法,或者您可以替換一個計算屬性,其中您將mention uder替換為a可以解析為不像router-link的元素:

 Vue.component('mention', { template: `<router-link:to="'/'+user">@{{user}}</router-link>`, props: ['user'] }) const Foo = { template: '<div>im foo</div>' } const Bar = { template: '<div>im bar</div>' } const routes = [{ path: '/foo', component: Foo }, { path: '/bar', component: Bar } ] const router = new VueRouter({ routes, // short for `routes: routes`, }) // 4. Create and mount the root instance. // Make sure to inject the router with the router option to make the // whole app router-aware. const app = new Vue({ router, data() { return { body: 'Hello im @foo and @bar' } }, computed: { tokens() { return this.body.split(' '); }, bodyReplaced() { return this.body.split(' ').map(w => { return w.startsWith('@')? `<a href="#/${w.slice(1)}">${w}</a>`: w; }).join(' ') } } }).$mount('#app')
 <script src="https://unpkg.com/vue/dist/vue.js"></script> <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script> <div id="app"> <div>********The first solution********</div> <template v-for="token in tokens"> <mention v-if="token.startsWith('@')":user="token.slice(1)"></mention> <template v-else>&nbsp;{{token}}&nbsp;</template> </template> <div>********The second solution********</div> <span v-html='bodyReplaced'></span> <router-view></router-view> </div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM