【问题标题】:Vue.js replace hashtags in text with <router-link>Vue.js 用 <router-link> 替换文本中的主题标签
【发布时间】:2018-04-26 17:04:12
【问题描述】:

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

示例文字是:“今天#weather 非常好”

以下代码将字符串转换为

Today <router-link to="/tag/weather">#weather</router-link> is very nice

但它不会再次呈现给&lt;a&gt; 标签。

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

【问题讨论】:

    标签: javascript vuejs2 vue-router routerlink


    【解决方案1】:

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

    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>

    【讨论】:

    • 非常感谢理查德,现在好多了,但现在仍然可以按照我想要的方式工作。现在它只保留主题标签作为链接并删除其余部分。它也不支持多个主题标签。是否可以保持文本原样,只转换带有链接的每个主题标签?
    • 实际上当用 元素包装text 时解决了我的问题。谢谢你的帮助:)
    • 您好,请小心 XSS 漏洞.. 因为内容呈现为 html
    猜你喜欢
    • 2020-04-05
    • 2020-11-13
    • 1970-01-01
    • 2016-01-17
    • 1970-01-01
    • 2013-06-19
    • 2020-02-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多