Today As the First Day of learning of Vue.js What i started with is the reactivity of Vue.js 2 and reactivity of Vue 3.
1.Vue 2 Reactivity
It works using setter and getter function that are passed as in an object as arguments of Object.defineproperty();
Object.defineProperty(info,"reactive_msg",//proxy for the info.msg
{
get(){
return info.msg
},
set(newValue){
info.msg = newValue;
document.getElementById("h1").innerText= newValue;
},
})
The Object.definePropety()->Accepts two values 1. The target object 2. Name of the new value 3.An object with the getter and setter object.
So with this it is clear that vue.js 2 works with the usage using setter and getter defined in the object.defineproperty();
In Vue 3 to implement reactivity it use the proxy constructor.
let info_proxy = new Proxy(info ,{
get(target,prop,receiver){
if(typeof target[prop] == 'string' ){
target[prop] = target[prop] + ' returned by proxy getter';
}
return Reflect.get(...arguments);
},
set(target,prop,newVal,receiver){
if(typeof newVal == 'string'){
newVal = newVal + ' returned by proxy setter';
}
document.getElementById("h1").innerText = newVal;
Reflect.set(...arguments)
},
}
)
The Proxy Constructor Accepts 2 values 1. The target object 2. Object with getter and setter
The getter function accepts 3 arguments 1.The target,2. Prop,3.Receiver
The setter function accepts 4 arguments 1.The target,2. Prop,3.the newval 4.receiver->as Name suggest the receiver of the new value
The Reflect.get() or Reflect.set() it is used to return our outputs as expected
To learn more about them follow this link Reflect Documentation
In Fig.2 as you can see the console it displays handler and target array the handler array contains
the setter and getter function
the target it contains the target in our case the msg in our info object.
As explained above below it is the display of our expanded info_proxy.
Vue 3 implementation it use proxy to create and update our dom as shown below as we run the instance of our app for the below implementation
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<script>
let app = Vue.createApp({
//options object
})
//mount
let vm = app.mount('#app');
</script>
As we console vm in our browser below is the output
Fig.5 shows us our get and set as same in our proxy constructor
As the figure above shows our target has more values than our proxy constructor and this is because we have targets that are already define as the same in our msg in info object in our proxy constructor
This is my first progress exploring Vue.js
Next lesson is learning about directives of vue.js
Top comments (5)
Well done on your first post exploring Vue.js. I am currently also learning Vue myself, I hope to be good at it before the end of the year.
Yeah i will be sharing my journey on dev.to today will share about the v-directives
Good one. Looking forward to it.
It's fine my friend. No pressure.