当前位置:网站首页>Object. Can defineproperty also listen for array changes?
Object. Can defineproperty also listen for array changes?
2022-06-25 08:48:00 【InfoQ】
Brief introduction
Object.defineProperty
Vue2
Object.defineProperty
Object.defineProperty
Vue2
Basic usage
Object.defineProperty()
grammar
Object.defineProperty(obj, prop, descriptor)
obj
The object to define the property .
prop
The name of the property to be defined or modified orSymbol
.
descriptor
Property descriptor to define or modify .
const data = {}
let name = ' Thunder monkey '
Object.defineProperty(data, 'name', {
get() {
console.log('get')
return name
},
set(newVal) {
console.log('set')
name = newVal
}
})
console.log(data.name)
data.name = ' Shark chilli '
console.log(data.name)
console.log(name)
get
Thunder monkey
set
Shark chilli
Shark chilli
data.name
name
name
data.name
name
const data = {}
Object.defineProperty(data, 'name', {
value: ' Thunder monkey ',
writable: false
})
data.name = ' Shark chilli '
delete data.name
console.log(data.name)
data.name
data.name
Thunder monkey
Object.defineProperty
Deep monitoring
// Trigger update view
function updateView() {
console.log(' View update ')
}
// Redefining properties , Listen up ( The core )
function defineReactive(target, key, value) {
// Deep monitoring
observer(value)
// The core API
Object.defineProperty(target, key, {
get() {
return value
},
set(newValue) {
if (newValue != value) {
// Deep monitoring
observer(newValue)
// Set new value
// Be careful ,value Always in closures , After setting here , Again get It will also get the latest value
value = newValue
// Trigger view update
updateView()
}
}
})
}
// Deep monitoring
function observer(target) {
if (typeof target !== 'object' || target === null) {
// Not an object or an array
return target
}
// Redefine each attribute (for in You can also iterate over groups )
for (let key in target) {
defineReactive(target, key, target[key])
}
}
// Prepare the data
const data = {
name: ' Thunder monkey '
}
// Start listening
observer(data)
// test 1
data.name = {
lastName: ' Shark chilli '
}
// test 2
data.name.lastName = ' Cockroach bully '
updateView
DOM
Vue
Object.defineProperty
set
observer(newValue)
observer
defineReactive
Listening array
key
Subscript
- Determine whether the data to be monitored is an array
- Is an array , Just simulate the array as an object
- Bind the method name of the array to the newly created object
- Assign the method corresponding to the array prototype to the custom method
// Trigger update view
function updateView() {
console.log(' View update ')
}
// Redefine array prototypes
const oldArrayProperty = Array.prototype
// Create new objects , Prototype pointing oldArrayProperty, Extending the new method will not affect the prototype
const arrProto = Object.create(oldArrayProperty);
['push', 'pop', 'shift', 'unshift', 'splice'].forEach(methodName => {
arrProto[methodName] = function() {
updateView() // Trigger view update
oldArrayProperty[methodName].call(this, ...arguments)
}
})
// Redefining properties , Listen up ( The core )
function defineReactive(target, key, value) {
// Deep monitoring
observer(value)
// The core API
Object.defineProperty(target, key, {
get() {
return value
},
set(newValue) {
if (newValue != value) {
// Deep monitoring
observer(newValue)
// Set new value
// Be careful ,value Always in closures , After setting here , Again get It will also get the latest value
value = newValue
// Trigger view update
updateView()
}
}
})
}
// Listening object properties ( entrance )
function observer(target) {
if (typeof target !== 'object' || target === null) {
// Not an object or an array
return target
}
// In the case of arrays
if (Array.isArray(target)) {
target.__proto__ = arrProto
}
// Redefine each attribute (for in You can also iterate over groups )
for (let key in target) {
defineReactive(target, key, target[key])
}
}
// Prepare the data
const data = {
nums: [10, 20, 30]
}
// Monitor data
observer(data)
data.nums.push(4) // Listening array
Array.prototype.push = function() {
updateView()
...
}
Array
Object.defineProperty
['push', 'pop', 'shift', 'unshift', 'splice']
Comprehensive code
// Deep monitoring
function updateView() {
console.log(' View update ')
}
// Redefine array prototypes
const oldArrayProperty = Array.prototype
// Create new objects , Prototype pointing oldArrayProperty, Extending the new method will not affect the prototype
const arrProto = Object.create(oldArrayProperty);
// arrProto.push = function () {}
// arrProto.pop = function() {}
['push', 'pop', 'shift', 'unshift', 'splice'].forEach(methodName => {
arrProto[methodName] = function() {
updateView() // Trigger view update
oldArrayProperty[methodName].call(this, ...arguments)
}
})
// Redefining properties , Listen up ( The core )
function defineReactive(target, key, value) {
// Deep monitoring
observer(value)
// The core API
// Object.defineProperty Does not have the ability to listen to arrays
Object.defineProperty(target, key, {
get() {
return value
},
set(newValue) {
if (newValue != value) {
// Deep monitoring
observer(newValue)
// Set new value
// Be careful ,value Always in closures , After setting here , Again get It will also get the latest value
value = newValue
// Trigger view update
updateView()
}
}
})
}
// Listening object properties ( entrance )
function observer(target) {
if (typeof target !== 'object' || target === null) {
// Not an object or an array
return target
}
if (Array.isArray(target)) {
target.__proto__ = arrProto
}
// Redefine each attribute (for in You can also iterate over groups )
for (let key in target) {
defineReactive(target, key, target[key])
}
}
summary
Vue 2
shortcoming
- Deep monitoring , You need to recurse to the end , A large amount of calculation
- Unable to listen for new properties / Delete attribute ( So we need to use Vue.set and Vue.delete)
- Cannot listen to native arrays , Require special treatment
Vue 3
Object.defineProperty
Proxy
Proxy
Vue 2
Vue 3
边栏推荐
- Swiperefreshlayout+recyclerview failed to pull down troubleshooting
- Sharepoint:sharepoint server 2013 and adrms Integration Guide
- What is the file that tp6 automatically executes? What does the tp6 core class library do?
- 软件测试月薪10K如何涨到30K,只有自动化测试能做到
- 【无标题】**数据库课设:三天完成学生信息管理系统**
- 初识生成对抗网络(11)——利用Pytorch搭建WGAN生成手写数字
- Trendmicro:apex one server tools folder
- Retrieval model rough hnsw
- City Chain technology platform, really Realizing value Internet reconstruction!
- LVS-DR模式单网段案例
猜你喜欢
How to solve the 10061 error of MySQL in Linux
linux中的mysql有10061错误怎么解决
cazy长安战役八卦迷宫
WebGL谷歌提示内存不够(RuntimeError:memory access out of bounds,火狐提示索引超出界限(RuntimeError:index out of bounds)
How to design test cases
Cazy eight trigrams maze of Chang'an campaign
Incluxdb time series database
What are the indicators of VIKOR compromise?
Getting to know the generation confrontation network (11) -- using pytoch to build wgan to generate handwritten digits
C language: find all integers that can divide y and are odd numbers, and put them in the array indicated by B in the order from small to large
随机推荐
对常用I/O模型进行比较说明
mysql之Unknown table ‘COLUMN_STATISTICS‘ in information_schema (1109)
【MYSQL】索引的理解和使用
Various synchronous learning notes
Is it really safe to pay new debts? Is it risky
openid是什么意思?token是什么意思?
Incluxdb time series database
QSS buttons of different styles
C language: count the number of characters, numbers and spaces
In Section 5 of bramble pie project practice, Nokia 5110 LCD is used to display Hello World
Data preprocessing: discrete feature coding method
[515. find the maximum value in each tree row]
OpenFOAM:底层
WebGL发布之后不可以输入中文解决方案
compiling stm32f4xx_it.c... “.\Objects\BH-F407.axf“ - 42 Error(s), 1 Warning(s).
Hyper-v:Hyper-v 第 1 代或第 2 代虚拟机
华泰证券在上面开股票账户安全吗?
故障:Outlook 收发邮件时的 0x800CCC1A 错误
软件测试月薪10K如何涨到30K,只有自动化测试能做到
How to become a software testing expert? From 3K to 17k a month, what have I done?