vue2给data的数据添加值的时候为什么push可以绑定数据,但是直接赋值不可以?

data属性:

a: {},
b: [],

在created的时候从服务器获取数据,需要填充到a和b中,因为数据需要过滤所以不能直接赋值,

for(let key in response.data.list){
    if(response.data.list[key].type == 2){
        this.a[key] = response.data.list[key]
    }
}

修改a的值时,视图不会刷新。
看了文档说是因为a的属性中没有key,新增的属性要$set。

但是,对b的操作有两种结果。
这样操作:

for(let key in response.data.list){
    if(response.data.list[key].type == 1){
        this.b.push(response.data.list[key])
    }
}

修改b的值,视图会刷新。
如果是这样:

let index = 0;
for(let key in response.data.list){
    if(response.data.list[key].type == 1){
        this.b[index] = response.data.list[key]
        index ++
    }
}

修改b的值,视图不会刷新。
为什么push的时候不需要$set?

阅读 5k
3 个回答

vue会对数组的原生方法进行劫持

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

vue数据双向绑定依赖于Object.defineProperty( ),而这个东西对数组的变动无法检测,所以你的arr[i]怎么变,对vue来说它不知道,当然视图也不会跟新;所以你有两种方法:1、将你筛选的arrry先用一个数组arr保存,然后一次性this.b = arr(引用数居的指针变了,vue会对这个值重新init,视图会更新);2、this.b[index] = response.data.list[key]换成this.b.push(response.data.list[key])--(vue封装的方法,就是说data里的每个属性的prototype上都重写了这个方法,push操作是会使对应的视图更新)

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题