In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
What is the principle of Vue monitoring data, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.
I. introduction
First of all, draw a simple picture.
We always deal with data when writing Vue, write our target data in data, and then render the data responsively in the difference expression of template in the format of {{xxx}}. When the data in data changes, the orange line here causes the difference expression to change. So the question is, how do we detect changes in data in data? The problem of Vue monitoring data is involved here.
II. Why do monitoring objects 2.1 need monitoring objects
First, write out the static pages that you need to use.
Update data {{p.name}}-{{p.age}} = {{p.sex}} Vue.config.productionTip = false const vm = new Vue ({el:'# root' Data: {persons: [{id:'001',name:' Black Cat Chiang', age: 20, sex: 'unknown'}, {id:'002',name:' White Cat Chiang', age: 23, sex: 'male'}, {id:'003',name:' Cat Chiang', age: 18 Sex: 'female'}]}})
Now let's assume that there is a requirement to add a button on the page through which the data with id 002 can be modified.
Click to modify White Cat methods: {change () {this.persons [1] .name = 'White Horse' this.persons [1] .age = 17 this.persons [1] .sex = 'unknown'}}
Attribute-by-attribute modification can change the data whose id is 002, but is this a bit tedious? can we change such a long period of modification into an object?
This.persons [1] = {id:'002',name:' White Horse', age: 17, sex: 'unknown'}
At this point, after clicking the button in the browser, the page does not respond. However, surprisingly, in the vm instance object, the data of persons [1] has indeed been changed!
To solve this problem, we can first look at another example, then see the specific execution process by typing it into the browser, and then come back to see the problem after understanding how to monitor it.
2.2 data Agent
To understand data monitoring, you also need to understand a pre-concept: data proxies.
Monitoring object Vue.config.productionTip = false const vm = new Vue ({el:'# root', data: {name: 'black cat', age: 20}})
In the past, if we wanted to access the data in data, we could get the specific value directly through the instance object, such as vm.name,vm.age. In fact, this is a simplified way of writing after doing a data agent.
Vue processes the data once, putting the data in data into _ data, and the instance object can get the processed data through. _ data. It's just that the value of the property is no longer given directly, but is obtained through the get method, which is somewhat similar to the getter method used in object-oriented languages such as JAVA to obtain private variables within a class. There is also a set method. When the data value in the data changes, the set method is called, which causes the template to be parsed again, then a new virtual DOM is generated to compare the new DOM with the old DOM, and finally the page is updated.
In fact, the source code is involved here, we do not consider the source code in this article, otherwise it will be too complicated. To put it simply, there is actually a method within Vue:
Vm._data = data = new Observer (data)
In the Observer function, first get all the attributes of data through Object.keys to form an array, then traverse the array, use Object.defineProperty to achieve data hijacking, and finally give the final result of the calculation to _ data.
2.3ObjectMonitoring Vue.set of related API
Or go to the static page first.
Update data School name: {{name}} School address: {{address}} Student name: {{student.name}} Student gender: {{student.sex}} Student Age: {{student.age}} Friends {{f.name}}- {{f.age}} Vue.config.productionTip = false const vm = new Vue ({el:'# root' Data: {name:'MIT', address:'UUU', student: {name:' tom', age: 20, friends: [{name:' jack', age: 21} {name: 'mary', age: 20}]},}})
You may notice that the sex that appears in template does not actually exist in data. When you output an attribute value that does not exist in an object, undefined is output, but the Vue does not display an undefined value after processing, that is, there is a null value after the student gender on the page, and there is no error on the console. Now come up with a need if we need to add a new gender attribute to the student. The requirement is that the existing data in data cannot be changed, that is, sex cannot be put directly into data.
Based on the _ data described earlier, we can try to bind the sex attribute directly through _ data. Then I found that it was not rendered to the page. In fact, this is a bit similar to the problem in 2.1. Let's make an analysis.
Let's print the _ data of vm first. As you can clearly see from the following figure, the sex property name and unknown property value have been successfully added to the student object. But moving on, there is no method for sex among the many get and set methods below, which means that the added attribute does not become responsive data.
To solve this problem, we can use the API provided by Vue, that is, the Vue.set () method, to make the later added data responsive. The first parameter of the method, target, indicates to whom the data is to be added, the second parameter, key, indicates the name of the attribute to be added, and the third parameter represents the property value.
At this point we can use Vue.set (vm._data.student,'sex',' unknown'), not only can change the properties in _ data, but also can be monitored to change the data in the page. There is also an api with the same effect, that is, vm.$set, which has the same usage as Vue.set () and the same parameters, vm.$set (vm._data.student,'sex',' unknown'). The data added by these two methods can become responsive data.
After implementing the function, we can consider the optimized shorthand, because the data proxy, vm.student = = vm._data.student, can be abbreviated to Vue.set (vm.student,'sex',' unknown).
Next, to verify the idea in the browser in the actual coding, suppose you add the sex attribute by clicking a button, so you won't describe it too much here, just paste the code.
Update data Click the button to add gender School name: {{name}} School address: {{address}} Student name: {{student.name}} Student gender: {{student.sex}} Student Age: {{student.age}} Friends {{f.name}}-{{f.age}} Vue.config.productionTip = false const vm = new Vue ({el:'# root' Data: {name:'MIT', address:'UUU', student: {name:' tom', age: 20, friends: [{name:' jack', age: 21} {name: 'mary', age: 20}]},}, methods: {addSex () {/ / in methoods The point of this is the vm instance object / / here it can also be written as this.$set (this.student, 'sex',' male') Vue.set (this.student, 'sex',' male')})
However, using this method has some limitations. When the addition is successful, it is set to the student object in data, so what if it is set directly to the data object? For example, suppose you need to add a new attribute, the founding date time, here, and if you still use the Vue.set method, you will get an error.
This shows that this method can only be used to add a new property to a responsive object (such as data.student here) and trigger a view update. Because Vue cannot detect normal new property.
2.4 assign multiple new values to an object
Sometimes you may need to assign multiple new property to existing objects, such as using Object.assign () or _ .extend (). However, a new property added to the object in this way does not trigger an update. So in this case, you should create a new object with the original object together with the property of the object you want to blend in.
For example, if I want to add height and weight attributes to student that didn't exist before, I can do this:
Const add = {'height': 180, "weight": 150} this.student = Object.assign ({}, this.student, add)
The original object and the new object are merged and assigned to an empty new object, then the object is assigned to the this.student, and the final data can be added to the student responsively.
III. Monitoring array
Still go to the static page first.
Update data Click the button to add gender School name: {{name}} School address: {{address}} Student name: {{student.name}} Student gender: {{student.sex}} Student Age: {{student.age}} Friends {{f.name}}-{{f.age}} hobby {{h}} Vue.config.productionTip = false const vm = new Vue ({el:'# root' Data: {name:'MIT', address:'UUU', student: {name:' tom', age: 20, friends: [{name:' jack', age: 21} {name: 'mary', age: 20}], hobby: [' eat', 'sleep', 'hit beans']},}, methods: {addSex () {this.$set (this.student, 'sex') 'male')})
After printing vm._data in the console, we can clearly see that for the hobby array in student, the array as a whole has get and set, which is responsive. But the elements in the array are not responsive, but simply hang in the array, which is why, in 2.1, when we try to reassign the array index subscript, there is no response on the page. If you change the hobby array to an object and print it again, you will find that the properties in the object are responsive. From this we can roughly guess that in Vue, if you want to modify the values in the array through the index, you need to use some special methods.
Where does the method come from? Now we can take a look at what the Vue document says. There is a paragraph on the page of document list rendering-> Array Update Detection-> change method:
Vue wraps the change methods of the listening array, so they will also trigger view updates. These packaged methods include:
Push () pop () shift () unshift () splice () sort () reverse ()
To modify the data in the array, we might as well try the above seven methods. If you look at these methods, you may think of the methods on the Array prototype chain, but they are not entirely true here. Vue encapsulates these methods once. When Vue parses these methods, the first step is still to call the methods in the Array prototype chain normally, and the second step is to re-parse the template, which is why you can use these methods to trigger view updates, because after re-parsing the template, you will generate a new virtual DOM to compare the new and old DOM, and finally update the page. This idea can be confirmed by the judgment of vm._data.student.hobby.push = = Array.prototype.push as false.
For example, here, what should we do if we want to modify Doudou for learning in hobby?
I will use the following code before I come into contact with these knowledge points, followed by an incorrect rendering. The page is not updated after the data has been changed.
This.student.hobby [2] = 'Learning'
Next, let's try two methods. First, try the array operation just introduced.
This.student.hobby.splice (2, 5, 3, learning)
Next, try the Vue.set method introduced earlier.
In addition, in 2.3, when we use this method to modify values in an object, the second parameter of the method is the attribute name, while when using this method in an array, the second parameter should be the subscript of the element in the array.
This.$set (this.student.hobby,2,' Learning')
Both methods can successfully modify the data in hobby and update it to the page.
In general, you cannot assign a value through the index value of an array. But you can change the direction of the array itself. As we have seen in the previous picture, the hobby array itself is responsive and can be monitored through get and set. For example, filter is used in business logic to filter arrays and then assign values to arrays that already exist in data. Here we can take a look at the introduction to the replacement array section in the documentation. Methods such as filter, concat, and slice do not change the original array, but always return a new array, and when using the change method, you can replace the old array with the new array.
Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.