Luuman's Blog

因为有了危机感,所以会义无反顾。


  • Home

  • About

  • Archives

  • Search

Vue defineProperty 双向绑定详解

Posted on 2017-08-18 Edited on 2019-10-18 In FrontFrame

Vue组件探秘双向绑定的实现方法有很多,今天我们来讲基于数据劫持的双向绑定。基于数据劫持的双向绑定有两种。Object.defineProperty与proxy,而VUE 3.0中使用的proxy
proxy 严格来说是代理,而非劫持。究竟什么优点让他代替了defineproperty。

框架原理方法
KnockoutJS基于观察者模式的双向绑定
Ember基于数据模型的双向绑定
Angular基于脏检查的双向绑定
Vue基于数据劫持的双向绑定Object.defineproperty
Vue基于数据劫持的双向绑定proxy
Vue基于数据劫持的双向绑定Object.observe(已废弃)

原理

Object.defineproperty

obj: 目标对象
prop: 需要操作的目标对象的属性名
descriptor: 描述符

return value 传入对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const obj = {}
Object.defineProperty(obj, 'text', {
get: function() {
console.log('get Val')
},
set: function(val) {
console.log('set val:' + val)
document.getElementById('p').innerHTML = val
}
})
const input = document.getElementById('input')
input.addEventListener('keyup', function (e){
obj.text = e.target.value
})

请输入:

# Vue
Vue组件探秘
keep-alive最佳实践
  • Table of Contents
  • Overview

Luuman

爱折腾,爱运动,更爱游离于错综复杂的编码与逻辑中,无法自拔。相信编程是一门艺术,自诩为游弋在代码里的人生。
92 posts
19 categories
36 tags
友情链接
  • 编程の趣
  • 翁天信
  • MOxFIVE
  • Meicai
  1. 1. 原理
广告位 广告位 广告位
© 2019 Luuman
Powered by Hexo v3.9.0
|
Theme – Nice.Gemini v7.3.0