iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 9
3
自我挑戰組

vue.js 30天學習軌跡系列 第 9

Day9 vue.js - 迴圈v-for

  • 分享至 

  • twitterImage
  •  

使用v-for多次渲染元素或模板塊

陣列

v-for="( 疊代的元素 , 索引 ) in 要抓取的資料"

DEMO

<ul>
    <li v-for="(item,index) in foodsArray"><span>{{index}} : {{item.name}} - {{item.price}}元</span></li>
  </ul>
var vm = new Vue({
  el:'#app',
  data:{
    foodsArray:[
      {
        id: 1,
        name: '薯條',
        price: 20,
      },
      {
        id: 2,
        name: '甜不辣',
        price: 20,
      },
      {
        id: 3,
        name: '雞排',
        price: 55,
      },
    ],
  },
})

物件

v-for="( 疊代的元素 , 鍵值 ,索引 ) in 要抓取的資料"

DEMO

<li v-for="(item,value,index) in foodsObj"><span>{{value}}  {{index}}: {{item.name}} - {{item.price}}元</span></li>
var vm = new Vue({
  el:'#app',
  data:{
     foodsObj:{
      eat:{
        name: '薯條',
        price: 20,
      },
      fried:{
        name: '甜不辣',
        price: 20,
      },
      drink:{
        name: '可樂',
        price: 25,
      },
    },
  },
})

:key

Vue 在更新 DOM 時是異步執行的。
若不設定 key 值,不會重新渲染元素,只會部份更新。
所以可給每個元素加上:key ,key值必須綁定一個唯一值,也就是確保每個元素的唯一性。

未使用 key

使用 key

DEMO

<ul> 
    <li class="keyli" v-for="(item,index) in foodsArray" :key="item.id">
        <span>{{index}}: {{item.name}} - {{item.price}}元</span>
      <input/>
    </li>
  </ul>
  <button @click="reverse">反轉</button>
var vm = new Vue({
  el:'#app',
  data:{
    foodsArray:[
      {
        id: 1,
        name: '薯條',
        price: 20,
      },
      {
        id: 2,
        name: '甜不辣',
        price: 20,
      },
      {
        id: 3,
        name: '雞排',
        price: 55,
      },
    ],
  },
  methods:{
    reverse(){
      this.foodsArray.reverse()
    }
  }
})

使用數字做迴圈

<span v-for=" item in 10">{{item}} </span>

template應用

可將輸出群組化,且template不會被輸出

<ul>
    <template v-for="(item,index) in foodsArray" :key="item.id">
      <li><span>{{item.name}}</span></li>
      <li><span>{{item.price}}</span></li>
    </template>
  </ul>

然後...明天見/images/emoticon/emoticon06.gif


上一篇
Day8 vue.js -v-model 雙向綁定(1)
下一篇
Day10 vue.js - v-model 雙向綁定 (2)
系列文
vue.js 30天學習軌跡30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言