下面代码实现了数据代理的基本流程
//这是index.js代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="../js/vue.js"></script>
</head>
<body>
<script>
let vm = new Vue({
data: {
message: 1
},
watch: {
message() {
console.log('message 发生了变化')
}
}
})
</script>
</body>
</html>
//这是index.js 代码
class Vue {
constructor(options) {
this.$options = options
//TODD:data 也可能是函数
this._data = options.data
this.initData()
}
initData() {
let data = this._data
let keys = Object.keys(data)
for (let i = 0; i < keys.length; i++) {
Object.defineProperties(this, keys[i], {
enumerable: true,
configurable: true,
get: function proxyGetter() {
return data[keys[i]]
},
set: function proxySetter(value) {
data[keys[i]] = value
}
})
}
}
}