Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the situations where the Vue data is updated but the page is not updated?

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly explains "what happens when the Vue data is updated but the page is not updated". Interested friends might as well take a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what happens when the Vue data has been updated but the page has not been updated.

1. Vue cannot detect property that does not exist in data when the instance is created.

Reason: because Vue performs getter/setter transformations on property when initializing the instance, property must exist on the data object for Vue to convert it to responsive.

Scene:

Var vm = new Vue ({data: {}, / / the page will not change template:'{{message}}'}) vm.message = 'hellograms' / / `vm.message` is not responsive

Solution:

Var vm = new Vue ({data: {/ / declare a, b as a null string message:',}, template:'{message}}'}) vm.message = 'hellogged'

2. Vue cannot detect the addition or removal of object property

Reason: official-due to the limitation of JavaScript (ES5), Vue.js cannot detect the addition or deletion of object attributes. Because Vue.js converts the property to getter/setter when initializing the instance, the property must be on the data object for Vue.js to transform it for it to be responsive.

Scene:

Var vm = new Vue ({data: {obj: {id: 001}}, / / the page will not change template:'{{obj.message}}'}) vm.obj.message = 'hello' / / is not responsive delete vm.obj.id / / is not non-responsive

Solution:

/ / dynamically add-Vue.set Vue.set (vm.obj, propertyName, newValue) / / dynamically add-vm.$set vm.$set (vm.obj, propertyName, newValue) / / dynamically add multiple / / replace `Object.assign (this.obj, {a: 1, b: 2}) `this.obj = Object.assign ({}, this.obj, {a: 1, b: 2}) / / dynamically remove-Vue.delete Vue.delete (vm.obj) PropertyName) / / dynamic removal-vm.$delete vm.$delete (vm.obj, propertyName)

3. Vue cannot detect the direct modification of an array item using an array index

Reason: officially-due to the limitations of JavaScript, Vue cannot detect changes in arrays and objects; you Yuxi-the performance cost is not proportional to the user experience.

Scene:

Var vm = new Vue ({data: {items: ['axed,' baked,'c']}}) vm.items [1] ='x' / / is not responsive

Solution:

/ / Vue.set Vue.set (vm.items, indexOfItem, newValue) / / vm.$set vm.$set (vm.items, indexOfItem, newValue) / / Array.prototype.splice vm.items.splice (indexOfItem, 1, newValue)

Extension: Object.defineProperty () can monitor array changes

However, adding an attribute (index) to the array does not detect data changes, because the subscript (index) of the new array cannot be detected, and so is deleting an attribute (index).

Scene:

Var arr = [1,2,3,4] arr.forEach (function (item, index) {Object.defineProperty (arr, index, {set: function (value) {console.log ('trigger setter') item = value}) Get: function () {console.log ('trigger getter') return item}}) arr [1] =' 123'/ / trigger setter arr [1] / / trigger getter return value of "123" arr [5] = 5 / / setter and getter will not be triggered

4. Vue cannot monitor the change of the length of the modified array.

Reason: officially-due to the limitations of JavaScript, Vue cannot detect changes in arrays and objects; you Yuxi-the performance cost is not proportional to the user experience. (Object.defineProperty () can monitor changes in data)

Scene:

Var vm = new Vue ({data: {items: ['axed,' baked,'c']}}) vm.items.length = 2 / / is not responsive

Solution:

Vm.items.splice (newLength)

5. Manipulating the DOM data does not change until the asynchronous update is executed

Reason: Vue executes asynchronously when updating DOM. Whenever a data change is detected, Vue opens a queue and buffers all data changes that occur in the same event loop. If the same watcher is triggered multiple times, it will only be pushed into the queue once. This removal of duplicate data during buffering is important to avoid unnecessary calculations and DOM operations. Then, in the next event loop "tick", Vue refreshes the queue and performs the actual (deduplicated) work. Vue internally tries to use native Promise.then, MutationObserver, and setImmediate for asynchronous queues, and uses setTimeout (fn, 0) instead if the execution environment does not support it.

Scene:

{{message}} var vm = new Vue ({el:'# example', data: {message: '123'}}) vm.message =' new message' / / change data vm.$el.textContent = = 'new message' / / false vm.$el.style.color =' red' / / the page has not changed

Solution:

Var vm = new Vue ({el:'# example', data: {message: '123'}}) vm.message =' new message' / / change data / / use Vue.nextTick (callback) callback will be called Vue.nextTick after the DOM update is complete (function () {vm.$el.textContent = 'new message' / / true vm.$el.style.color =' red' / / text color turns red}))

Extension: misunderstanding of data response caused by asynchronous updates

{{message.text}} var vm = new Vue ({el:'# example', data: {message: {},}}) vm.$nextTick (function () {this.message = {} this.message.text ='I updated!' })

In the previous code, we declared an empty message object in the data object, and then executed the following two pieces of code in the asynchronous callback triggered after the end of the next DOM update loop:

This.message = {}; this.message.text ='I updated!'

At this point, the template has been updated, and the page will finally show that I have updated.

The template has been updated and should be responsive, and if you think so, then you have entered a misunderstanding.

At first, we just declared an empty message object in the data object and did not have the text property, so the text property was not responsive.

But the template has actually been updated, so what's going on?

That is because the DOM update of Vue.js is asynchronous, that is, when the setter operation occurs, the instruction will not be updated immediately, and there will be a delay in the instruction update operation. When the instruction update is actually executed, the text attribute has been assigned, so the instruction updates the template with a new value.

Each instruction / data binding in the template has a corresponding watcher object that records the attributes as dependencies during the calculation. Later, when the dependent setter is called, the watcher recalculation is triggered, which causes its associated instruction to update the DOM.

The specific process is as follows:

Setter is called when this.dataObj = {}; is executed.

When the setter that Vue.js traces to the message dependency is called, it triggers the watcher recalculation.

This.message.text = 'new text'; assigns the text attribute.

After the execution of the asynchronous callback logic ends, it causes its associated instruction to update DOM, and the instruction update begins to execute.

So the real operation that triggers the template update is this.message = {}; this sentence causes, because setter is triggered, so if you look at the above example, only message is the layer of data with responsive characteristics, and its dynamically added attributes are not available.

Corresponding to the second point above-Vue cannot detect the addition or removal of object property

6. The loop nesting level is too deep and the view is not updated.

See some people on the Internet say that the level of data update is too deep, resulting in data not updated or slow to update, resulting in an attempt not to update?

Since I have not encountered this situation, when I tried to reproduce the scene, I found that this did not happen, so do not describe this too much (leave a message if someone encounters this situation in a real situation).

The solution given to the above situation is to use forced updates:

If you find yourself needing a mandatory update in Vue, 99.9% of the cases are that you did something wrong somewhere.

Vm.$forceUpdate ()

7. Expansion: when routing parameters change, the page is not updated (data is not updated)

Expand a problem that the page is not updated because of the change of routing parameters. The fact that the page is not updated is essentially that the data is not updated.

Reason: when the routing view component references the same component, when the routing parameter changes, it will cause the component to not be updated, which is the problem that the page cannot be updated.

Scene:

To Foo To Baz To Bar const Home = {template: `{{message}}`, data () {return {message: this.$route.params.name} const router = new VueRouter ({mode:'history', routes: [{path:'/ home', component: Home}, {path:'/ home/:name' Component: Home}]}) new Vue ({el:'# app', router})

In the previous code, we configured a dynamic route'/ home/:name', in the route building option routes. They share a routing component, Home, which means they reuse RouterView.

When a route switch is made, the page will only render the parameters to which the first route matches, and when the route switch is made later, the message will not change.

Solution: there are many solutions, here is only one method that I often use.

Listen for changes to $route through watch.

Const Home = {template: `{message}}`, data () {return {message: this.$route.params.name}}, watch: {'$route': function () {thisthis.message = this.$route.params.name}. New Vue ({el:'# app', router})

Here you are

Bind the key property so that Vue thinks this is different

.

Disadvantages: if we jump from / home to other routes such as / user, we don't have to worry about component updates, so the key attribute is superfluous at this time.

... At this point, I believe that everyone has a deeper understanding of "Vue data has been updated but the page is not updated". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report