2017-08-09 247 views
0

我想在表格中顯示三個不同的json列表。第一個包含網址,谷歌地圖的第二個網址和最後一條消息。Vue js在表格中插入鏈接

以使其我有一個模板是這樣的:

<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\.)?[[email protected]:%._\+~#=]{1,256}\.[a-z]{2,4}\b([[email protected]:%_\+.~#?&//=]*)/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 
}] 

回答

2

您可以格式化模板的URL像這樣:

<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> 
+0

在沒想到。這麼簡單...謝謝! –