This is the 14th day of my participation in the August More Text Challenge. For details, see:August is more challenging

preface

Good evening, everyone. In your spare time, let’s continue the topic of yesterday, the responsive principle of Vue2 object.defineProperty () – part 2.

The use of object.defineProperty () in VUE is reflected

First write section vue instance demo, code as follows:

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="./node_modules/vue/dist/vue.js"></script> <script> const The vm = new Vue ({el: "# app," data: {title: 'look at lushan waterfall, poets: {dynasty:' in the tang dynasty, the name: "li bai"}}}) < / script > < / body >Copy the code

The effect is as follows:

This is what a simple data rendering view looks like, but it’s easy to see why some data must be defined in data first and then used this. This syntax can take values or define values, such as data returned from the back end, and assign values to pre-defined data or objects. This is because object.defineProperty () has the inherent defect that if an Object adds a property, that property is not responsive. So in order to guarantee the response before using the data, it must be defined in data.

Like the one printed in the console below, with {… } is the hijacked object property, which executes the get function when we access it, as we mentioned in the last video.When we rename the poet, we synchronize the response to the DOM and change the view, as shown here:

Next we want to attach something to the poem, enter the following on the console:

However, it is found that there is no change in the browser. This is because the new object properties are not defined in data. Adding them is not responsive and will not be synchronized, but the properties are added, as shown in the figure:

How to solve the problem that new attributes are responsive

The vue.set() method is available on the vue.set() website, as is the case with vm.$set(). Vue. Set through train

The syntax structure is as follows: vue.set (target, propertyName/index, value) Parameter 1: the object that sets the property parameter 2: What property is added to the object Parameter 3: the value of the new property

Correct writing

Vue.set(vm.poets, ‘first’, ‘Poets by Day ‘)