1

我从服务器收到一些可能包含一些主题标签的文本,当显示此文本时,我想用链接转换这些标签。

示例文本是:“今天#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 这种方法,但它希望整个字符串是单个链接而不是一些文本和一些链接。

4

1 回答 1

4

您的代码似乎适合动态链接组件。

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');
<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>

于 2017-11-14T08:13:33.833 回答