【问题标题】:Making links in the text of a div clickable使 div 文本中的链接可点击
【发布时间】:2021-12-24 06:58:03
【问题描述】:

我正在尝试使用 Nuxt/Vue 使文本中的 URL 可点击。

输入文本是: Learning Outside the Box - https://learningoutsidethebox.com

我有一个方法可以将其转换为链接:

setLinks(text) {
  var Rexp = /(\b(https?|ftp|file):\/\/([-A-Z0-9+&@#%?=~_|!:,.;]*)([-A-Z0-9+&@#%?\/=~_|!:,.;]*)[-A-Z0-9+&@#\/%=~_|])/ig;
              
  return text.replace(Rexp, "<NuxtLink to='$1' target='_blank'>$1</NuxtLink>");
}

之后我得到一个结果:Learning Outside the Box - &lt;NuxtLink to='https://learningoutsidethebox.com' target='_blank'&gt;https://learningoutsidethebox.com&lt;/NuxtLink&gt;。但是还是不能点击。

更改为&lt;a&gt; 并没有解决问题。

您能否澄清一下,我应该怎么做才能使此文本成为有效链接?

【问题讨论】:

  • 将其生成为文本确实不会使其支持 Vue。为什么你甚至首先使用这个正则表达式?你不能动态传递值吗? setLinks 是什么?
  • 1) 为什么你一开始还要使用这个正则表达式? - 以它为例stackoverflow.com/questions/49899107/… 2)你能澄清一下,我应该在哪里通过它?这是用户创建的帖子的内容吗? setLinks 用链接替换 ​​URL
  • &lt;nuxt-link :to="dataComingFromTheUser"&gt;&lt;/nuxt-link&gt; 实际上应该足够了。如果您需要稍微按摩一下,可以使用computed
  • 另外,不要将a 标记用于 SPA 内部的内部链接,否则您需要从头开始重新生成。

标签: javascript vue.js hyperlink nuxt.js


【解决方案1】:

你可以试试a标签和v-html

new Vue({
  el: '#demo',
  data() {
    return {
      url: 'Learning Outside the Box - https://learningoutsidethebox.com'
    }
  },
  computed: {
    getLink() {
      return this.setLinks(this.url)
    }
  },
  methods: {
    setLinks(text) {
      const Rexp = /(\b(https?|ftp|file):\/\/([-A-Z0-9+&@#%?=~_|!:,.;]*)([-A-Z0-9+&@#%?\/=~_|!:,.;]*)[-A-Z0-9+&@#\/%=~_|])/ig;
      return text.replace(Rexp, "<a href='$1' target='_blank'>$1</a>");
    }
  }
})

Vue.config.productionTip = false
Vue.config.devtools = false
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <div v-html="getLink"></div>
</div>

【讨论】:

  • 谢谢!但是,我会考虑更新我的解决方案,因为它可能会导致 XSS
  • @PavelShepelenko 阅读这篇文章:stackoverflow.com/a/69074884/8816585
  • 谢谢,用v-dompurify-html代替v-html
猜你喜欢
  • 1970-01-01
  • 2011-09-27
  • 2022-07-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-29
  • 2014-10-06
  • 1970-01-01
相关资源
最近更新 更多