列表渲染v-for


v-for我們用v-for指令根據一組數據的選項列表進行渲染。v-for指令需要以item in items形式的特殊語法,items是源數據數組並且item是數組元素迭代的別名。

demo:

<ul>

  <li v-for="item in items">{{item}}</li>

</ul>

 

data:{

  items:[1,2,3,4,5,6,7,8]

}

 

渲染的結果

<ul>

  <li>1</li>

  <li>2</li>

  <li>3</li>

  <li>4</li>

  <li>5</li>

  <li>6</li>

  <li>7</li>

  <li>8</li>

</ul>

在v-for塊中,我們擁有對父作用域屬性的完全訪問權限。v-for還支持一個可選的第二個參數作為當前項的索引。

<ul>

  <li v-for="(index,item) in items">{{index}}:{{item}}</li>

</ul>
<ul>

  <li>0:1</li>

  <li>1:2</li>

  <li>2:3</li>

  <li>3:4</li>

  <li>4:5</li>

  <li>5:6</li>

  <li>6:7</li>

  <li>7:8</li>

</ul>

Template v-for

如同v-if模板,你也可以用帶有v-for的<template>來渲染多個元素塊

<ul>
  <template v-for="item in items">
    <li>{{ item.msg }}</li>
    <li class="divider"></li>
  </template>
</ul

對象迭代 v-for

你也可以使用v-for通過一個對象的屬性來迭代

<ul>
        <li v-for="obj in object">{{obj}}</li>
    </ul>
data:{
    object:{
                name:"zhangsan",
                 age:20,
                  sex:"男"
              }
}

整數迭代v-for

v-for 也可以取整數,在這種情況下,它將重復多次模板。

<div>

  <span v-for="n in 3">{{n}}</span>

</div>

渲染的結果是:

<div>

  <span>1</span>

  <span>2</span>

  <span>3</span>

</div>

組件和v-for

在自定義組件里,你可以像任何普通元素一樣用 v-for 。

<my-component v-for="item in items"></my-component>
<my-component
v-for="(item, index) in items"
v-bind:item="item"
v-bind:index="index">
</my-component>

然而他不能自動傳遞數據到組件里,因為組件有自己獨立的作用域。為了傳遞迭代數據到組件里,我們要用 props :

不自動注入 item 到組件里的原因是,因為這使得組件會緊密耦合到 v-for 如何運作。在一些情況下,明確數據的來源可以使組件可重用。

下面是一個簡單的 todo list 完整的例子:

<div id="todo-list-example">
<input
v-model="newTodoText"
v-on:keyup.enter="addNewTodo"
placeholder="Add a todo"
>
<ul>
<li
is="todo-item"
v-for="(todo, index) in todos"
v-bind:title="todo"
v-on:remove="todos.splice(index, 1)"
></li>
</ul>
</div>

 

Vue.component('todo-item', {
template: '\
<li>\
{{ title }}\
<button v-on:click="$emit(\'remove\')">X</button>\
</li>\
',
props: ['title']
})
 
new Vue({
el: '#todo-list-example',
data: {
newTodoText: '',
todos: [
'Do the dishes',
'Take out the trash',
'Mow the lawn'
]
},
methods: {
addNewTodo: function () {
this.todos.push(this.newTodoText)
this.newTodoText = ''
}
}
})

顯示過濾/排序結果

有時,我們想要顯示一個數組的過濾或排序副本,而不實際改變或重置原始數據。在這種情況下,可以創建返回過濾或排序數組的計算屬性。

例如:

<li v-for="n in evenNumbers">{{ n }}</li>

 


data: { numbers: [
1, 2, 3, 4, 5 ] }, computed: { evenNumbers: function () { return this.numbers.filter(function (number) { return number % 2 === 0 }) } }

<li v-for="n in even(numbers)">{{ n }}</li>或者,你也可以在計算屬性不適用的情況下 (例如,在嵌套 v-for 循環中) 使用 method 方法:


data: { numbers: [
1, 2, 3, 4, 5 ] }, methods: { even: function (numbers) { return numbers.filter(function (number) { return number % 2 === 0 }) } }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM