Vue js在表中插入链接

时间:2017-08-09 17:45:31

标签: javascript vuejs2

我想在表格中显示三个不同的json列表。第一个包含URL,第二个包含谷歌地图和最后一条消息。

为了呈现它,我有一个这样的模板:

<script type="text/x-template" id="grid-template">
  <table class="table">
    <thead>
      <tr>
        <th v-for="key in columns"
          @click="sortBy(key)"
          :class="{ active: sortKey == key }">
            ${ key | capitalize }
          <span class="arrow" :class="sortOrders[key] > 0 ? 'asc' : 'dsc'">
          </span>
        </th>
      </tr>
    </thead>
    <tbody>
      <tr v-for="entry in filteredData">
        <td v-for="key in columns">${isUrl(key,entry[key])}</td>
      </tr>
    </tbody>
  </table>
</script>


  Vue.component('demo-grid', {
    template: '#grid-template',
    delimiters: ['${', '}'],
    props: {
      data: Array,
      columns: Array,
      filterKey: String
    },
    data: function () {
      var sortOrders = {}
      this.columns.forEach(function (key) {
        sortOrders[key] = 1
      })
      return {
        sortKey: '',
        sortOrders: sortOrders
      }
    },
    computed: {
      filteredData: function () {
        var sortKey = this.sortKey
        var filterKey = this.filterKey && this.filterKey.toLowerCase()
        var order = this.sortOrders[sortKey] || 1
        var data = this.data
        if (filterKey) {
          data = data.filter(function (row) {
            return Object.keys(row).some(function (key) {
              return String(row[key]).toLowerCase().indexOf(filterKey) > -1
            })
          })
        }
        if (sortKey) {
          data = data.slice().sort(function (a, b) {
            a = a[sortKey]
            b = b[sortKey]
            return (a === b ? 0 : a > b ? 1 : -1) * order
          })
        }
        return data
      }
    },
    filters: {
      capitalize: function (str) {
        return str.charAt(0).toUpperCase() + str.slice(1)
      }
    },
    methods: {
      sortBy: function (key) {
        this.sortKey = key
        this.sortOrders[key] = this.sortOrders[key] * -1
      },

      isUrl: function (key, str){
        if (key == "url"){
          var exp = /^((?:https?|ftp):\/\/.)?(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-z]{2,4}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)/ig;
          return str.replace(exp,"<a :href='$1'>$1</a>");
        }
        else{
          console.log("ej")
          return str
        }
      }
    }

  })

我想在列中创建一个超链接。键名是"url",但是vue会自动转义。如何设置替换超链接的文本?

数据的一个例子:

[{
  "date": "2017-08-09 18:25:06.226631", 
  "id": 5, 
  "private": true,
  "reviewed": false, 
  "title": "To Protect Voting, Use Open-Source Software - NYTimes.com", 
  "url": "j.mp/2upm633", 
  "user": 1
}]

1 个答案:

答案 0 :(得分:3)

您可以像这样格式化模板中的网址:

<tr v-for="entry in filteredData">
  <td v-for="key in columns">
    <template v-if="key === 'url'">
      <a :href="entry[key]">${ entry[key] }</a>
    </template>
    <template v-else>
      ${ entry[key] }
    </template>
  </td>
</tr>