07-vue.js-列表渲染

1.用 v-for 把一個數(shù)組對應(yīng)為一組元素

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

<ul id="example-1">
  <li v-for="item in items">
    {{ item.message }}
  </li>
</ul>
var example1 = new Vue({
  el: '#example-1',
  data: {
    items: [
      { message: 'Foo' },
      { message: 'Bar' }
    ]
  }
})

結(jié)果:

  • Foo
  • Bar

v-for 塊中,我們擁有對父作用域?qū)傩缘耐耆L問權(quán)限。v-for 還支持一個可選的第二個參數(shù)為當前項的索引。

<ul id="example-2">
  <li v-for="(item, index) in items">
    {{ parentMessage }} - {{ index }} - {{ item.message }}
  </li>
</ul>
var example2 = new Vue({
  el: '#example-2',
  data: {
    parentMessage: 'Parent',
    items: [
      { message: 'Foo' },
      { message: 'Bar' }
    ]
  }
})

結(jié)果:

  • Parent - 0 - Foo
  • Parent - 1 - Bar

你也可以用 of 替代 in 作為分隔符,因為它是最接近 JavaScript 迭代器的語法:

<div v-for="item of items"></div>

2.一個對象的 v-for

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

<ul id="v-for-object" class="demo">
  <li v-for="value in object">
    {{ value }}
  </li>
</ul>
new Vue({
  el: '#v-for-object',
  data: {
    object: {
      title: 'How to do lists in Vue',
      author: 'Jane Doe',
      publishedAt: '2016-04-10'
    }
  }
})

結(jié)果:

  • How to do lists in Vue
  • Jane Doe
  • 2016-04-10

你也可以提供第二個的參數(shù)為 property 名稱 (也就是鍵名):第三個參數(shù)為索引:

<div v-for="(value, name, index) in object">
  {{ index }}. {{ name }}: {{ value }}
</div>

0. title: How to do lists in Vue

1. author: Jane Doe

2. publishedAt: 2016-04-10

在遍歷對象時,是按 Object.keys() 的結(jié)果遍歷,但是不能保證它的結(jié)果在不同的 JavaScript 引擎下是一致的。

3.維護狀態(tài)

當 Vue.js 用 v-for 正在更新已渲染過的元素列表時,它默認用“就地復(fù)用”策略。如果數(shù)據(jù)項的順序被改變,Vue 將不會移動 DOM 元素來匹配數(shù)據(jù)項的順序, 而是簡單復(fù)用此處每個元素,并且確保它在特定索引下顯示已被渲染過的每個元素。

這個默認的模式是高效的,但是只適用于不依賴子組件狀態(tài)或臨時 DOM 狀態(tài) (例如:表單輸入值) 的列表渲染輸出。

為了給 Vue 一個提示,以便它能跟蹤每個節(jié)點的身份,從而重用和重新排序現(xiàn)有元素,你需要為每項提供一個唯一 key 屬性

<div v-for="item in items" v-bind:key="item.id">
  <!-- 內(nèi)容 -->
</div>

建議盡可能在使用 v-for 時提供 key attribute,除非遍歷輸出的 DOM 內(nèi)容非常簡單,或者是刻意依賴默認行為以獲取性能上的提升。

因為它是 Vue 識別節(jié)點的一個通用機制,key 并不與 v-for 特別關(guān)聯(lián),key 還具有其他用途,我們將在后面的指南中看到其他用途。

不要使用對象或數(shù)組之類的非原始類型值作為 v-forkey。用字符串或數(shù)類型的值取而代之。

數(shù)組更新檢測

變異方法

Vue 包含一組觀察數(shù)組的變異方法,所以它們也將會觸發(fā)視圖更新。這些方法如下

  • push()
  • pop()
  • shift()
  • unshift()
  • splice()
  • sort()
  • reverse()

你打開控制臺,然后用前面例子的 items 數(shù)組調(diào)用變異方法:example1.items.push({ message: 'Baz' }) 。

替換數(shù)組

變異方法 (mutation method),顧名思義,會改變被這些方法調(diào)用的原始數(shù)組。相比之下,也有非變異 (non-mutating method) 方法,例如:filter(), concat()slice() 。這些不會改變原始數(shù)組,但總是返回一個新數(shù)組。當使用非變異方法時,可以用新數(shù)組替換舊數(shù)組:

example1.items = example1.items.filter(function (item) {
  return item.message.match(/Foo/)
})

你可能認為這將導(dǎo)致 Vue 丟棄現(xiàn)有 DOM 并重新渲染整個列表。幸運的是,事實并非如此。Vue 為了使得 DOM 元素得到最大范圍的重用而實現(xiàn)了一些智能的、啟發(fā)式的方法,所以用一個含有相同元素的數(shù)組去替換原來的數(shù)組是非常高效的操作。

注意事項

由于 JavaScript 的限制,Vue 不能檢測以下變動的數(shù)組:

  1. 當你利用索引直接設(shè)置一個項時,例如:vm.items[indexOfItem] = newValue
  2. 當你修改數(shù)組的長度時,例如:vm.items.length = newLength

舉個例子:

var vm = new Vue({
  data: {
    items: ['a', 'b', 'c']
  }
})
vm.items[1] = 'x' // 不是響應(yīng)性的
vm.items.length = 2 // 不是響應(yīng)性的

為了解決第一類問題,以下兩種方式都可以實現(xiàn)和 vm.items[indexOfItem] = newValue 相同的效果,同時也將觸發(fā)狀態(tài)更新:

// Vue.set
Vue.set(vm.items, indexOfItem, newValue)
// Array.prototype.splice
vm.items.splice(indexOfItem, 1, newValue)

你也可以使用 vm.$set 實例方法,該方法是全局方法 Vue.set 的一個別名:

vm.$set(vm.items, indexOfItem, newValue)

為了解決第二類問題,你可以使用 splice

vm.items.splice(newLength)

對象更改檢測注意事項

還是由于 JavaScript 的限制,Vue 不能檢測對象屬性的添加或刪除

var vm = new Vue({
  data: {
    a: 1
  }
})
// `vm.a` 現(xiàn)在是響應(yīng)式的

vm.b = 2
// `vm.b` 不是響應(yīng)式的

對于已經(jīng)創(chuàng)建的實例,Vue 不能動態(tài)添加根級別的響應(yīng)式屬性。但是,可以使用 Vue.set(object, propertyName, value) 方法向嵌套對象添加響應(yīng)式屬性。例如,對于:

var vm = new Vue({
  data: {
    userProfile: {
      name: 'Anika'
    }
  }
})

你可以添加一個新的 age 屬性到嵌套的 userProfile 對象:

Vue.set(vm.userProfile, 'age', 27)

你還可以使用 vm.$set 實例方法,它只是全局 Vue.set 的別名:

vm.$set(vm.userProfile, 'age', 27)

有時你可能需要為已有對象賦予多個新屬性,比如使用 Object.assign()_.extend()。在這種情況下,你應(yīng)該用兩個對象的屬性創(chuàng)建一個新的對象。所以,如果你想添加新的響應(yīng)式屬性,不要像這樣:

Object.assign(vm.userProfile, {
  age: 27,
  favoriteColor: 'Vue Green'
})

你應(yīng)該這樣做:

vm.userProfile = Object.assign({}, vm.userProfile, {
  age: 27,
  favoriteColor: 'Vue Green'
})

顯示過濾/排序結(jié)果

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

例如:

<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
    })
  }
}

在計算屬性不適用的情況下 (例如,在嵌套 v-for 循環(huán)中) 你可以使用一個 method 方法:

<li v-for="n in even(numbers)">{{ n }}</li>
data: {
  numbers: [ 1, 2, 3, 4, 5 ]
},
methods: {
  even: function (numbers) {
    return numbers.filter(function (number) {
      return number % 2 === 0
    })
  }
}

一段取值范圍的 `v-for

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

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

結(jié)果:

1 2 3 4 5 6 7 8 9 10

v-for on a <template>

類似于 v-if,你也可以利用帶有 v-for<template> 渲染多個元素。比如:

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

v-for with v-if

注意我們推薦同時使用 v-ifv-for

當它們處于同一節(jié)點,v-for 的優(yōu)先級比 v-if 更高,這意味著 v-if 將分別重復(fù)運行于每個 v-for 循環(huán)中。當你想為僅有的一些項渲染節(jié)點時,這種優(yōu)先級的機制會十分有用,如下:

<li v-for="todo in todos" v-if="!todo.isComplete">
  {{ todo }}
</li>

上面的代碼只傳遞了未完成的 todos。

而如果你的目的是有條件地跳過循環(huán)的執(zhí)行,那么可以將 v-if 置于外層元素 (或 <template>)上。如:

<ul v-if="todos.length">
  <li v-for="todo in todos">
    {{ todo }}
  </li>
</ul>
<p v-else>No todos left!</p>

一個組件的 v-for

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

<my-component v-for="item in items" :key="item.id"></my-component>

2.2.0+ 的版本里,當在組件中使用 v-for 時,key 現(xiàn)在是必須的。

然而,任何數(shù)據(jù)都不會被自動傳遞到組件里,因為組件有自己獨立的作用域。為了把迭代數(shù)據(jù)傳遞到組件里,我們要用 props

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

不自動將 item 注入到組件里的原因是,這會使得組件與 v-for 的運作緊密耦合。明確組件數(shù)據(jù)的來源能夠使組件在其他場合重復(fù)使用。

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

<div id="todo-list-example">
  <form v-on:submit.prevent="addNewTodo">
    <label for="new-todo">Add a todo</label>
    <input
      v-model="newTodoText"
      id="new-todo"
      placeholder="E.g. Feed the cat"
    >
    <button>Add</button>
  </form>
  <ul>
    <li
      is="todo-item"
      v-for="(todo, index) in todos"
      v-bind:key="todo.id"
      v-bind:title="todo.title"
      v-on:remove="todos.splice(index, 1)"
    ></li>
  </ul>
</div>

注意這里的 is="todo-item" 屬性。這種做法在使用 DOM 模板時是十分必要的,因為在 <ul> 元素內(nèi)只有 <li> 元素會被看作有效內(nèi)容。這樣做實現(xiàn)的效果與 <todo-item> 相同,但是可以避開一些潛在的瀏覽器解析錯誤。查看 DOM 模板解析說明 來了解更多信息。

Vue.component('todo-item', {
  template: '\
    <li>\
      {{ title }}\
      <button v-on:click="$emit(\'remove\')">Remove</button>\
    </li>\
  ',
  props: ['title']
})

new Vue({
  el: '#todo-list-example',
  data: {
    newTodoText: '',
    todos: [
      {
        id: 1,
        title: 'Do the dishes',
      },
      {
        id: 2,
        title: 'Take out the trash',
      },
      {
        id: 3,
        title: 'Mow the lawn'
      }
    ],
    nextTodoId: 4
  },
  methods: {
    addNewTodo: function () {
      this.todos.push({
        id: this.nextTodoId++,
        title: this.newTodoText
      })
      this.newTodoText = ''
    }
  }
})
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 這篇筆記主要包含 Vue 2 不同于 Vue 1 或者特有的內(nèi)容,還有我對于 Vue 1.0 印象不深的內(nèi)容。關(guān)于...
    云之外閱讀 5,167評論 0 29
  • 主要還是自己看的,所有內(nèi)容來自官方文檔。 介紹 Vue.js 是什么 Vue (讀音 /vju?/,類似于 vie...
    Leonzai閱讀 3,535評論 0 25
  • Vue 實例 屬性和方法 每個 Vue 實例都會代理其 data 對象里所有的屬性:var data = { a:...
    云之外閱讀 2,361評論 0 6
  • 1. Vue 實例 1.1 創(chuàng)建一個Vue實例 一個 Vue 應(yīng)用由一個通過 new Vue 創(chuàng)建的根 Vue 實...
    王童孟閱讀 1,089評論 0 2
  • vue概述 在官方文檔中,有一句話對Vue的定位說的很明確:Vue.js 的核心是一個允許采用簡潔的模板語法來聲明...
    li4065閱讀 7,589評論 0 25

友情鏈接更多精彩內(nèi)容