vue.js 如何才能从后端的数据,一个文本与链接成为可点击的前端?

5us2dqdw  于 2023-05-01  发布在  Vue.js
关注(0)|答案(1)|浏览(190)

例如,我有这个objects of array

const data = [
  { name: 'John', age: 25, 'body' : "this data has link https://stackoverflow.com/questions/ask" },
  { name: 'Jane', age: 31, 'body' : "this data has link https://stackoverflow.com/questions/ask" },
  { name: 'Bob', age: 18, 'body' : "this data has link https://stackoverflow.com/questions/ask" }
];

如何在frontend中显示时使其变为link

68de4m5k

68de4m5k1#

如果我理解正确,请看下面的片段:

const { reactive, computed } = Vue
const app = Vue.createApp({
  setup() {
    const mydata = reactive([
      { name: 'John', age: 25, 'body' : "this data has link https://stackoverflow.com/questions/ask" },
      { name: 'Jane', age: 31, 'body' : "this data has link https://stackoverflow.com/questions/ask" },
      { name: 'Bob', age: 18, 'body' : "this data has link https://stackoverflow.com/questions/ask" }
    ])
    const formatedData = computed(() => {
      const expression = / *https:.+/
      return mydata.map(d => {
        let link = d.body.match(expression)
        d.body = d.body.replace(expression, ` <a href="${link}">${link}</a>`)
        return d
      })
    })
    return { mydata, formatedData }
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div v-for="(dat, i) in formatedData" :key="i">
    <p>{{ dat.name }} - <span>{{ dat.age }}</span></p>
    <div v-html="dat.body"></div>
  </div>
</div>

相关问题