iT邦幫忙

0

(已解決)Vue.js v-for 顯示問題

想請教

<span v-for="(item, index) in list">
    {{ item }}, 
</span>

假如 list 長度是 3 則顯示在頁面上會是
item0, item1, item2,

我希望最後一個小逗號(,)能不顯示變成
item0, item1, item2
請問應該怎麼做呢
謝謝

list資料可以先在在computed做完逗號的處理再去v-for做渲染
小斑 iT邦新手 3 級 ‧ 2021-11-08 15:39:05 檢舉
謝謝
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中
1
鮮黃色的獅
iT邦新手 5 級 ‧ 2021-11-05 10:28:39
最佳解答
<span>
    {{ list.join(",") }}
</span>
小斑 iT邦新手 3 級 ‧ 2021-11-08 15:39:25 檢舉

謝謝

1
Homura
iT邦高手 1 級 ‧ 2021-11-04 15:49:51

如果你陣列裡面很單純只是string的話可以這樣寫

{{ list.toString() }}

如果裡面是物件的話還是建議用computed計算完再回傳

{{ listString }}

<script>
new Vue({
  el: '#example',
  data: {
    list: [{a:1},{a:2}]
  },
  computed: {
    
    listString: function () {
      let arr = []
      this.list.forEach(item=>{
          arr.push(item.a)
      })
      
      return arr.toString()
    }
  }
})
</script>
小斑 iT邦新手 3 級 ‧ 2021-11-08 15:39:15 檢舉

謝謝

0
gior__ann
iT邦新手 2 級 ‧ 2021-11-05 13:53:28

{{ }} 也可以加入 function
提供其中一個方法,不一定是最好的寫法~

如果 index 為最後一個,則不加上 ,

<span v-for="(item, index) in list">
  {{ filterText(item,index) }}
</span>

....

methods:{
    filterText(val, idx){
      if(idx < this.list.length - 1){
        return val + ","
      }
      return val
    }
}

https://ithelp.ithome.com.tw/upload/images/20211105/201207225qhpvrRi1b.jpg

完整如下,提供參考
codepen

小斑 iT邦新手 3 級 ‧ 2021-11-08 15:39:44 檢舉

謝謝

我要發表回答

立即登入回答