Post

Vue 是如何重写数组绑定的?

Vue 是如何重写数组绑定的?

Vue 2 如何重写数组方法?

Vue 2 通过 Array.prototype 继承的方式,创建了一个 自定义的数组原型对象,然后让响应式数组继承这个对象,并在其中拦截了能够修改数组的方法,如 pushpopshiftunshiftsplicesortreverse

核心代码

以下是 Vue 2 源码中关于 数组方法劫持 的核心代码:

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// src/core/observer/array.js

/*
 * not type checking this file because flow doesn't play well with
 * dynamically accessing methods on Array prototype
 */
// def: src/core/util/lang.js
// def => Object.defineProperty  
import { def } from '../util/index'
// 获取数组的原型
const arrayProto = Array.prototype
// 创建一个新的对象,并继承 Array.prototype
export const arrayMethods = Object.create(arrayProto)

/**
 * Intercept mutating methods and emit events
 */
;[
  'push',
  'pop',
  'shift',
  'unshift',
  'splice',
  'sort',
  'reverse'
] 
.forEach(function (method) { // 遍历需要拦截的方法
  // 先保存原始方法
  const original = arrayProto[method]
  
  // 重写方法。def直接在一个对象上定义一个新属性,或修改其现有属性,并返回此对象。
  def(arrayMethods, method, function mutator () {
    // avoid leaking arguments:
    // http://jsperf.com/closure-with-arguments
    let i = arguments.length
    const args = new Array(i)
    while (i--) {
      args[i] = arguments[i]
    }
    
    // 调用原始方法
    const result = original.apply(this, args)
    // 获取 Observer 实例
    const ob = this.__ob__
    // 处理新增元素(push、unshift、splice)
    let inserted
    switch (method) {
      case 'push':
        inserted = args
        break
      case 'unshift':
        inserted = args
        break
      case 'splice': // splice(起始索引, 删除个数, 插入元素...)
        inserted = args.slice(2)
        break
    }
    // 对新插入的元素进行响应式处理
    if (inserted) ob.observeArray(inserted)
    // 通知依赖更新
    ob.dep.notify()
    return result
  })
})

示例:Vue 数组响应式

例子:

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
28
<template>
  <div>
    <h2>Vue 2 数组响应式示例</h2>
    <ul>
      <li v-for="(item, index) in items" :key="index"></li>
    </ul>
    <button @click="addItem">Push 新元素</button>
    <button @click="removeItem">Pop 删除元素</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      items: ['苹果', '香蕉', '橙子']
    };
  },
  methods: {
    addItem() {
      this.items.push('葡萄'); // 触发 Vue 2 监听
    },
    removeItem() {
      this.items.pop(); // 触发 Vue 2 监听
    }
  }
};
</script>

执行步骤

  1. 页面初始渲染:

    1
    2
    3
    4
    5
    
    <ul>
      <li>苹果</li>
      <li>香蕉</li>
      <li>橙子</li>
    </ul>
    
  2. 点击 Push 新元素 按钮,调用 this.items.push('葡萄')

    • Vue 通过 push 方法拦截新增数据,并自动触发视图更新。
    • this.items 变为 ['苹果', '香蕉', '橙子', '葡萄'],DOM 重新渲染。
  3. 点击 Pop 删除元素 按钮,调用 this.items.pop()

    • Vue 通过 pop 方法拦截数据删除,并自动触发视图更新。
    • this.items 变回 ['苹果', '香蕉', '橙子'],DOM 重新渲染。

Vue 2 监听数组的局限

虽然 Vue 2 对数组方法进行了劫持,但它仍然有一些监听上的局限:

  1. 直接修改数组索引无法触发视图更新

    1
    
    this.items[1] = '';  // 视图不会更新!
    

    解决方案

    • 直接修改 this.items,而不是修改索引。

    • 使用 Vue.set()$set() 强制更新:

      1
      
      this.$set(this.items, 1, ''); // 视图会更新!
      
  2. 修改 length 无法触发更新

    1
    
    this.items.length = 2; // 视图不会更新!
    

    解决方案

    • 使用 splice()

      1
      
      this.items.splice(2); // 视图会更新!
      
This post is licensed under CC BY 4.0 by the author.