Vue_ 渲染列表

v-for把陣列轉換為一組元素

將item拿出來當作屬性

自訂所需資料在陣列裡,使用動態屬性分別套入不同顏色(css設定)
資料匯入的過程新增一組判斷式,當key值為A則顯示紅色,B則顯示藍色,利用動態屬性更改色系
這裡與之前案例的內容相同,也是使用:class綁定屬性的顏色(經由css修改)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<div id="app">
<ol>
<li v-for="item in todo" v-bind:class='item.key'>
{{item.date}} {{item.content}}
</li>
</ol>
</div>


new Vue({
el:'#app',
data:{
todo:[{key:'first',date:'3/9',content:'學習javascrip'},
{key:'second',date:'3/10',content:'學會vue框架'},
{key:'second',date:'3/11',content:'做作品'},
{key:'second',date:'3/12',content:'準備面試'}]
},
})

<style>
.first{
color:red;
}
.second{
color:green;
}
</style>

陣列新增、刪減、排列基本語法

  • push(ew item)從陣列後面新增
  • pop()從陣列後面刪減
  • unshift(new item)從陣列前面新增
  • shift()從陣列前面刪減

<div id="app">
  <ul>
    <li v-for="item in steps">{{item}}</li>
  </ul>
  <button @click="push">Push</button>
  <button @click="pop">Pop</button>
  <button @click="shift">Shift</button>
  <button @click="unshift">Unshift</button>
</div>

new Vue({
  el:'#app',
  data:{
    steps:[1,2,3,4,5],
  },
  methods:{
    push(){
      this.steps.push(this.steps.length+1);
    },
    pop(){
      this.steps.pop();
    },
    shift(){
      this.steps.shift();
    },
    unshift(){
      this.steps.unshift(0);
    },

  }
})

用v-for渲染templete

每次迴圈需要被render出來的不只一個元素,而是包含多個標籤元素,可以使用templete>,並將v-for指令放在templete標籤中。

<div id="app">
  <template v-for='item in header'>
    <h1>{{item}}</h1>
    <hr/>
  </template>
</div>

new Vue({
  el:'#app',
  data:{
    header:['Home','About','Product','Contact']
  },
  methods:{

  }
})