<!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> </head> <body> <h2>vue如何让每个月属性都可被观测</h2> <script type="module"> import { Observer } from './observer.js' let obj = new Observer( { name:'小明', age:18 } ) console.log(obj.value.name) obj.value.age = 25 </script> </body> </html>
export class Observer{ constructor(value){ this.value = value if(Array.isArray(value)){ // 数组重写。。 }else{ this.walk(value) } } walk(obj){ const keys = Object.keys(obj) for(let i= 0;i<keys.length;i++){ defineReactive(obj,keys[i]) } } } //循环 让对象每个属性可观测 function defineReactive(obj,key,val){ if(arguments.length ===2){ val = obj[key] } if( typeof val === 'object'){ //递归 } Object.defineProperty(obj,key,{ enumerable:true, //可枚举 configurable:true,//可改变 get: function(){ console.log("取之",val) return val }, set: function(b){ console.log(b,"改之") val = b } }) }
标签:obj,Observer,keys,value,walk,vue2,做到,监听 From: https://www.cnblogs.com/zhuangdd/p/17275655.html