vue之set(加深印象)

问题:

添加和编辑功能同用一个模态框,并且反写数据时候,form表单里的数据并没有回显

原因:

当生成vue实例后,当再次给数据赋值时,有时候并不会自动更新到视图上去; 当我们去看vue文档的时候,会发现有这么一句话:如果在实例创建之后添加新的属性到实例上,它不会触发视图更新

底层原因:

受 ES5 的限制,Vue.js 不能检测到对象属性的添加或删除。因为 Vue.js 在初始化实例时将属性转为 getter/setter,所以属性必须在 data 对象上才能让 Vue.js 转换它,才能让它是响应的。

this.$set(that.consultForm, 'max_minute1', row.price_info[0].max_minute);
Vue.set()和this.$set()实现原理
//Vue.set()
import { set } from '../observer/index'

...
Vue.set = set
...
import { set } from '../observer/index'

...
Vue.prototype.$set = set
...

底层代码逻辑原理

function set (target: Array<any> | Object, key: any, val: any): any {
...
    if (Array.isArray(target) && isValidArrayIndex(key)) {
    target.length = Math.max(target.length, key)
    target.splice(key, 1, val)
    return val
  }
  if (key in target && !(key in Object.prototype)) {
    target[key] = val
    return val
  }
 if (!ob) {
    target[key] = val
    return val
  }
  //重要,重新触发getter和set
  defineReactive(ob.value, key, val)
  //通知更新到dom
  ob.dep.notify()
  return val
    
    
}

源码结论:
两者的底层原理都是一样的,
区别是Vue.set是绑定在构造函数上,
this.$set是绑定在vue的原型上

原文地址:https://www.cnblogs.com/hanhaiyuntao/p/15186366.html