Vue.js 将文本中的主题标签替换为 <router-link>

Vue.js replace hashtags in text with <router-link>

我从服务器收到一些文本,其中可能包含一些主题标签,在显示这些文本时,我想用 links 转换这些标签。

示例文本为:"Today #weather is very nice"

以下代码将字符串转换为

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/">#</router-link>')
        }
    },
    data() {
        return{
             content: 'Today #weather is very nice'
        };
    }

</script>

如何重新呈现内容?

我试过 https://codepen.io/movii/pen/WORoyg 这种方法,但它希望整个字符串是单个 link 而不是一些文本和一些 links。

您的代码似乎适合动态-link 组件。

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/">#</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');
<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>