我从服务器收到一些文本,其中可能包含一些主题标签,在显示此文本时,我想用链接转换这些标签。
示例文字是:“今天#weather非常好”
以下代码将字符串转换为
Today <router-link to="/tag/weather">#weather</router-link> is very nice
但它不会再次呈现给<a>
标记。
<template>
<p v-html="content"/>
</template>
<script>
export default {
methods: {
convertHashTags: function(str) {
return str.replace(/#([\w]+)/g,'<router-link to="/tag/$1">#$1</router-link>')
}
},
data() {
return{
content: 'Today #weather is very nice'
};
}
</script>
如何重新呈现内容?
我尝试https://codepen.io/movii/pen/WORoyg这种方法,但它希望整个字符串是单个链接而不是某些文本和一些链接。
答案 0 :(得分:3)
您的代码似乎适合动态链接组件。
console.clear()
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
const Weather = { template: '<div>weather</div>' }
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar },
{ path: '/tag/weather', component: Weather },
]
Vue.component('dynamic-link', {
template: '<component v-bind:is="transformed"></component>',
props: ['text'],
methods: {
convertHashTags: function(str) {
const spanned = `<span>${str}</span>`
return spanned.replace(/#([\w]+)/g,'<router-link to="/tag/$1">#$1</router-link>')
}
},
computed: {
transformed () {
const template = this.convertHashTags(this.text);
return {
template: template,
props: this.$options.props
}
}
}
})
const router = new VueRouter({ routes })
const app = new Vue({
router,
data () {
return {
text: 'Today #weather is very nice'
}
}
}).$mount('#app');
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<router-link to="/bar">Go to Bar</router-link> |
<dynamic-link :text="text"></dynamic-link>
<router-view></router-view>
</div>
&#13;