[英]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>'
)
}
}
代碼做了什么:
我想你正在尋找類似的東西
<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> {{token}} </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.