vue——ViewModel 简易原理

数据双向绑定简易原理

<input type="text" id="username">
<span id="uName"></span>
  let obj = {
   }
  Object.defineProperty(obj, 'username', {
   
  	// 使用 defineProperty 中的 get 来双向绑定数据
    set (v) {
   
      document.getElementById('uName').innerText = v;
      document.getElementById('username').value = v;
    },
    get () {
   
      console.log('get')
    }
  })
  document.getElementById('username').addEventListener('keyup', function (e) {
   
    obj.username = e.target.value
  })

defineProperty 实现原理

const vm = {
   
    name: 'bob',
    age: 11,
    enjoy: ['1', 'a', 3],
    hobby: {
    a: 'eat' }
}

const orginalProto = Array.prototype
const arrayProto = Object.create(orginalProto) // 先克隆份 Array 原型
const methodToPatch = [
    'push',
    'pop',
    'shift',
    'unshift',
    'splice',
    'sort',
    'reverse'
]
methodToPatch.forEach(method => {
   
    arrayProto[method] = function () {
   
        console.log('method changed: ', method, arguments)
        orginalProto[method].apply(this, arguments)
    }
})

const observe = (data) => {
   
    if (!data || typeof data !== 'object') return
    if (Array.isArray(data)) {
   
        // 如果是数组,重写原型链 data.__proto__ = arrayProto
        Object.setPrototypeOf(data, arrayProto);
        for (let i = 0; i < data.length; i++) {
   
            observe(data[i])
        }
    } else {
   
        Object.keys(data).forEach(key => {
   
            dr(data, key, data[key])
        })
    }
}

const dr = (data, key, val) => {
   
    observe(val) // 递归制造响应式数据
    Object.defineProperty(data, key, {
   
        enumerable: true,
        configurable: true,
        set(nv) {
   
            console.log('val changed: ', nv)
            val = nv
        },
        get() {
   
            return val
        }
    })
}

observe(vm)

vm.name = 'lucy'
vm.age = 11
vm.hobby.a = 'play'
vm.enjoy.push(123)
vm.sex = 'female' // 监听不到

// 问题:直接 watch 对象下某个属性监听不到
@Watch('searchList', {
    deep: true, immediate: true })
onSearchListWatch(newVal, oldVal) {
   
    const getSubBu = (list) => list?.find((item) => item.index === 1)?.subBuCode;
    if (getSubBu(newVal) !== getSubBu(oldVal)) {
   
        this.initLineList();
    }
}

// 解决
@Watch('oneSearchList', {
    deep: true, immediate: true })
onSearchListWatch(newVal, oldVal) {
   
    if (newVal !== oldVal) {
   
        this.initLineList(
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值