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 is the difference between computed and watch in Vue

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article shows you the difference between computed and watch in Vue. The content is concise and easy to understand. It will definitely brighten your eyes. I hope you can get something through the detailed introduction of this article.

1. Introduction of computed

Computed is used to monitor self-defined variables, which are not declared in data, but are directly defined in computed and can be used directly on the page.

/ / the foundation uses {{msg}} / / calculate the attribute computed: {msg:function () {return this.name}}

In the input box, when it is worthwhile to change the name, the msg will also change. This is because computed listens for its own property msg and finds that msg updates as soon as name changes.

Note: msg cannot be defined in data, otherwise an error will be reported.

1.1.The usage of get and set

Data () {return {first:' Beauty', second:' Sister'}}, computed: {full: {get () {/ / callback function is executed when reading the current attribute value, calculates and returns the current attribute value return this.first +''+ this.second} according to the relevant data, set (val) {/ / monitors the change of the current attribute value, and executes when the attribute value changes Update related attribute data let names = val.split ('') this.first = names [0] this.second = names [1]}}

Get method: when first and second change, the get method is called to update the value of full.

Set method: when the value of full is modified, the set method is called, and val is the latest value of full.

1.2. Calculation attribute cache

We can also achieve this effect by splicing the data. The code is as follows.

{{full ()}} data () {return {first:' Beauty', second:' Sister'}, methods: {full () {return this.first +'+ this.second}}

Data may be used many times in a page. We implement computed and method together, and refer to this data many times in the page. Try the following effect.

Computed calculated value: {{full}} {{full}} {{full}} methods calculated value: {{fullt}} {{fullt}} data () {return {first:' Beauty', second:' Sister'}, computed: {full:function () {console.log ('computed') return this.first +' + this.second}} Methods: {fullt () {console.log ('method') return this.first +''+ this.second}}

The running result is:

According to the results, it is not difficult to find that the data obtained by the method needs to be recalculated several times after using it several times, but the calculated properties are not cached based on their responsive dependencies, and then recalculated when the dependent property values change. Because it has fewer calculations, it has higher performance.

II. Introduction to watch

Watch is to monitor changes in data on an Vue instance. In popular terms, it is to detect the data declared in data. You can monitor not only simple data, but also objects or object properties.

Demo1: monitoring simple data

Data () {return {first:' Beauty',}}, watch: {first (newVal, oldVal) {the latest value of console.log ('newVal',newVal) / / first console.log (' oldVal',oldVal) / / the last value}} of first, / / when you change the value of first, the latest value will be printed immediately

Demo2: monitoring object

When listening to an object, you need to use deep monitoring.

Data () {return {per: {name:' Qianqian', age:'18'}}, watch: {per: {handler (oldVal,newVal) {console.log ('newVal',newVal) console.log (' oldVal',oldVal)}, deep:true,}}

When modifying per.name, it is found that the values of newVal and oldVal are the same, because their stored pointers point to the same place, so deep listening can listen for changes in objects, but cannot detect which properties have changed.

Demo3: a single property of the listening object

/ / method 1: directly reference the properties of the object data () {return {per: {name:' Qianqian', age:'18'}, watch: {'per.name':function (newVal,oldVal) {console.log (' newVal- >', newVal) console.log ('oldVal- >', oldVal)}

You can also use computed as an intermediate transformation, as follows:

/ / method 2: with the help of computed data () {return {per: {name:' Qianqian', age:'18'}, watch: {perName () {console.log ('name changed')}}, computed: {perName:function () {return this.per.name}}

Demo4: listen for the value passed by the props component

Props: {mm:String}, / / do not use immediatewatch: {mm (newV,oldV) {console.log ('newV',newV) console.log (' oldV',oldV)}} / / use immediatewatch: {mm: {immediate:true, handler (newV,oldV) {console.log ('newV',newV) console.log (' oldV',oldV)}}

When immediate is not used, printing in the mm that watch listens to is not performed the first time the page is loaded.

When using immediate, the result is also printed the first time it is loaded: newV 11 oldV undefined.

The main function of immediate is to trigger the callback function immediately when the component is loaded.

Third, the difference between the two 3.1, for computed

The data monitored by computed is not declared in data

Computed does not support asynchronism. When there is an asynchronous operation in computed, it cannot listen for changes in data.

Computed has cache, and the page is re-rendered. If the value is unchanged, the previous calculation result will be returned directly and will not be recalculated.

If an attribute is calculated from another attribute, this property depends on other properties, generally using computed

When computed calculates that a property value is a function, it defaults to the get method. If the attribute value is an attribute value, the property has a get and set method, and the set method is called when the data changes

Computed: {/ / attribute value is function perName:function () {return this.per.name}, / / attribute value is attribute value full: {get () {}, set (val) {}}, 3.2. for watch

The monitored data must be declared in data or data in props

Support for asynchronous operation

Without cache, when the page is re-rendered, it will be executed when the value does not change.

When the value of an attribute changes, you need to perform the corresponding action

When the listening data changes, other actions are triggered, and the function takes two parameters:

Immediate: the callback function is triggered immediately by component loading

Deep: deep snooping is mainly aimed at complex data, such as when listening to objects, add deep snooping, and any attribute value change will trigger.

Note: after adding deep snooping to the object, the old and new values are the same.

When the computed page is re-rendered, the calculation is not repeated, and watch is recalculated, so computed performance is higher.

IV. Application scenarios

When you need to do numerical calculations and rely on other data, you should use computed because you can take advantage of computed's caching feature to avoid having to recalculate every time you get a value.

When you need to perform asynchronous operations or expensive operations when the data changes, you should use watch,computed that does not support async. If you need to limit the frequency of operations, you can use computed as an intermediate state.

The above is the difference between computed and watch in Vue. Have you learned any knowledge or skills? If you want to learn more skills or enrich your knowledge reserve, you are welcome to follow the industry information channel.

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