vue 數組 新增元素 響應式原理 7種方法


1、問題

思考一個問題,以下代碼:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title>vue 數組 響應式原理</title>
    </head>
    <body>
        <div id="app">
            <div v-for="item in list"> {{ item }} </div>
        </div>

        <script src="https://cdn.bootcss.com/vue/2.5.17/vue.min.js"></script>
        <script type="text/javascript">
            var app = new Vue({ el: '#app', data: { list: [1, 2, 3] } }) </script>

    </body>
</html>

當我們在控制台輸入:app.list[0] = 100時,vue會監測到變化嗎?

 app.push(100)呢? 

 

 引申出的問題就是:

vue對數組新增的元素,包括push、unshift和splice(插入)的元素是怎么做到響應式的呢

 

2、Vue對新增的數組元素響應式原理

(1)核心代碼(observer/array.js)

/* * not type checking this file because flow doesn't play well with * dynamically accessing methods on Array prototype */ import { def } from '../util/index' const arrayProto = Array.prototype export const arrayMethods = Object.create(arrayProto) const methodsToPatch = [ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse' ] /** * Intercept mutating methods and emit events */ methodsToPatch.forEach(function (method) { // cache original method
  const original = arrayProto[method] def(arrayMethods, method, function mutator (...args) { const result = original.apply(this, args) const ob = this.__ob__ let inserted switch (method) { case 'push': case 'unshift': inserted = args break
      case 'splice': inserted = args.slice(2) break } if (inserted) ob.observeArray(inserted) // notify change
 ob.dep.notify() return result }) })

在這個函數中使用到了def函數,def函數的定義是(util/lang.js):

export function def (obj: Object, key: string, val: any, enumerable?: boolean) { Object.defineProperty(obj, key, { value: val, enumerable: !!enumerable, writable: true, configurable: true }) }

即對元素的屬性重新定義,尤其是value的獲取。

 

回到observer/array.js,除了正常返回push、unshift和splice(插入)函數執行的result結果外,還通知了變化!ob.dep.notify! 所以對新增的數組元素實現了響應式的變化。

 

留一個問題:

switch (method) { case 'push': case 'unshift': inserted = args break
      case 'splice': inserted = args.slice(2) break }

為什么push、unshift和splice處理的參數不一樣? 

查一下splice的參數有哪些吧。

 


免責聲明!

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



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