This is the 15th day of my participation in the August More Text Challenge. For details, see:August is more challenging
Preface:
Hello, friends, we meet again, the two days of the weekend has passed, let’s roll up our sleeves and work hard, a new week to sail. The first two days we talked about the responsive principle of VUE2, today, let’s learn the responsive principle of VUE3!
Vue3 Responsive principle – Proxy
Proxy constructor, not hijacking, means proxy, ES6 syntax, not attribute level, proxy the whole object.
The code for
<script> var poets = {dynasty: 'tang ', name: Const newPoets = new Proxy(poets, {// targe is the target) {console.log(' poets get(target, key) ', key); return target(key) }, set() { } }) </script>Copy the code
When we print a property of the object in the console, the object is propended and the corresponding property of the object is printed, as shown in the figure below:
Properties of an object can also be accessed using constructors
benefit
This makes it easy to proxy the object without worrying about which property of the object we are accessing. Because if you access any property of an object, you can just go through the get function and print it out.
Description of set() for proxy
The set function takes three arguments, set(target,key,value)
Parameter 1: the target object of the agent parameter 2: the property of the object operated parameter 3: the property value of the object set
The code is as follows:
Set (target, key,value) {console.log(' set ',key,value); poets[key] = value }Copy the code
The biggest benefit of proxy is that it operates the proxy object, but the ultimate effect is on the target object.
The benefits of the proxy
You don’t have to worry about adding properties that are not responsive, you can add them directly, because you are operating on the proxy object, the entire target object of the proxy.
Use of responsive data in VUE3
The < body > < div id = "app" > < h1 > the {{title}} < / h1 > < h3 class = "item" > {{poets. Dynasty}} - {{poets. The name}} < / h3 > <h3>{{poets.first}},{{poets.second}}</h3> </div> <script src="https://unpkg.com/vue@next"></script> <script> const App = {data() {return {title: 'Poets' : {dynasty:' tang ', name: 'li Bai ', first:'}, nameList: [' du fu, bai juyi, 'tu mu]}}} const vm = Vue. CreateApp (App). The mount (' # App) < / script > < / body >Copy the code
Vm. poets is a proxy for Poets. When we change the properties of an object, we see that the properties of the target object change in response.
When we add a nonexistent property to the proxy object, the target object also adds that property and updates the DOM