VUE basics (4): realize two-way binding

1. How does Vue achieve two-way binding?
Use Object.defineProperty to hijack the object's accessor. When the property value changes, we can get the change, and then make subsequent responses based on the change (similar operations are performed through the proxy object in vue3.0).

// 这是将要被劫持的对象 
const data = {
    
     name: '', };

function say(name) {
    
     
	if (name === ' 古 天 乐 ') {
    
     console.log('给⼤家推荐⼀款超好玩的游戏 '); } 
	else if (name === '渣渣辉') {
    
     console.log('戏我演过很多,可游戏我只玩贪玩懒⽉'); } 
	else {
    
     console.log('来做我的兄弟'); } }

// 遍历对象,对其属性值进⾏劫持
 Object.keys(data).forEach(function(key) {
    
     
 	Object.defineProperty(data, key, {
    
     
 		enumerable: true, 
 		configurable: true, 
 		get: function() {
    
     console.log('get'); },
 		set: function(newVal) {
    
     
 		// 当属性值发⽣变化时我们可以进⾏额外操作 
 		console.log(` ⼤ 家 好 , 我 系 ${
      
      newVal}`); 
 		say(newVal); },
 	}); 
 }); 
 data.name = '渣渣辉'; 
 //⼤家好,我系渣渣辉 
 //戏我演过很多,可游戏我只玩贪玩懒⽉

Guess you like

Origin blog.csdn.net/imagine_tion/article/details/110683536