首頁  >  文章  >  web前端  >  詳解Vue列表渲染

詳解Vue列表渲染

php中世界最好的语言
php中世界最好的语言原創
2018-03-08 17:29:452180瀏覽

這次帶給大家詳解Vue清單渲染,詳解Vue清單渲染的注意事項有哪些,下面就是實戰案例,一起來看一下。

變異方法 (mutation method),顧名思義,會改變被這些方法呼叫的原始陣列。相較之下,也有非變異 (non-mutating method) 方法,例如:filter(), concat() 和 slice() 。這些不會改變原始數組,但總是會傳回一個新數組。當使用非變異方法時,可以用新數組取代舊數組:

example1.items = example1.items.filter(function (item) {  return item.message.match(/Foo/)})
<div id="example">
  <div>
    <button @click="concat()">concat</button>
    <button @click="slice()">slice</button>
    <button @click="filter()">filter</button>
  </div>
  <ul>
    <li v-for="item in items">
      {{item.list}}
    </li>
  
  </ul>
</div>
<script>
  var example = new Vue({
    el:"#example",
    data:{
      items:[
        {list:5},
        {list:6},
        {list:7}
      
      ],
      addValue:{list:10}
    },
    methods:{
      concat(){
     this.items= this.items.concat(this.addValue)
      },
      slice(){
      this.items = this.items.slice(1)
      },
      filter(){
      this.items = this.items.filter(function(item,index,arr) {
          return (index > 0)
        })
      }
    
    }
  })

以上操作並不會導致Vue丟棄現有DOM並重新渲染整個列表。 Vue實作了一些智慧啟發式方法來最大化DOM元素重用,所以用一個含有相同元素的陣列去替換原來的陣列是非常高效的操作

注意事項

由於JavaScript 的限制,Vue 無法偵測以下變動的陣列:

當你利用索引直接設定一個項目時,例如:

vm.items[indexOfItem] = newValue

當你修改當陣列的長度時,例如:

vm.items.length = newLength

為了解決第一類問題,以下兩種方式都可以實現和vm.items[indexOfItem] = newValue 相同的效果,同時也會觸發狀態更新

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

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

example1.items.splice(newLength)

我相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

相關閱讀:

在HTML中如何用3499910bf9dac5ae3c52d5ede7383485標籤寫個人收藏夾

HTML用img標籤做圖

HTML裡的常見問題一

以上是詳解Vue列表渲染的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn