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

How to use Compute attribute and snooping property in Vue

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

Share

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

Today, the editor will share with you the relevant knowledge points about how to use the computing attributes and monitoring attributes in Vue. The content is detailed and the logic is clear. I believe most people still know too much about this knowledge, so share this article for your reference. I hope you can get something after reading this article. Let's take a look.

First, why should we use computational attributes? what are computational attributes?

Computational attributes: can be understood as attributes that can write some computational logic in it. It has the following functions:

Reduce the computational logic in the template.

Data caching. When there is no change in our data, the calculation process will not be performed again.

It depends on a fixed data type (responsive data) and cannot be a normal incoming global data.

When the amount of data is large, computational attributes can help us improve performance, because computational attributes are only calculated when the data changes.

Before we explain the calculation properties, let's take a look at the following example:

Demand: takeout package An is 15 yuan per order, the customer ordered 3, the total price is 20% discount, the distribution fee is 5 yuan, the total price is required to be displayed on the interface, the code is as follows:

You have purchased {{info.name}} a total of {{info.count}} total price: {{info.count*info.price*info.sale+info.freight}} Yuan export default {name:'Test', data () {return {info: {userId:1, price:15, name:' package Aids, count:3 Sale:0.8, freight:5}

Interface running effect:

Looking at the above example, some people may ask: the requirements have been implemented in this way, so why use computational properties? We know that expressions in templates in vue are very convenient and are originally designed for simple operations. If putting too much logic in the template can make the template overweight and difficult to maintain, take a look at the code above:

Total price: {{info.count*info.price*info.sale+info.freight}} yuan

In this code, the template is no longer a simple declarative logic, but a complex logical calculation, which can be difficult to maintain if you want to reference the total price in multiple places. Therefore, for any complex logic, you should use computational properties.

Take a look at the following example of using calculated properties:

Calculation attribute you purchased {{info.name}} total {{info.count}} total price: {{totalPrice}} Yuan export default {name:'ComputedDemo', data () {return {info: {userId:1, price:15, name:' package Aids, count:3 Sale:0.8, freight:5}}, computed: {/ / define calculation property totalPrice totalPrice:function () {return this.info.count*this.info.price*this.info.sale+this.info.freight}

Interface display effect:

Note: the evaluation property is a property, not a method, and cannot be written in methods, but placed in the computed attribute.

The above calculated attributes can also be written in ES6:

/ / use ES6 to write totalPrice () {return this.info.count*this.info.price*this.info.sale+this.info.freight} 2. Differences between calculation properties and methods 1. Differences

In addition to using calculation properties, the above example can also be implemented using methods:

Calculation property you have purchased {{info.name}} a total of {{info.count}}. Use the calculation attribute to get the total price: {{totalPrice} yuan. Use the method to get the total price: {{getTotalPrice ()}} yuan export default {name:'ComputedDemo', data () {return {info: {userId:1, price:15 Name:' package totalPrice, count:3, sale:0.8, freight:5}}, computed: {/ / define calculation attributes totalPrice / / totalPrice:function () {/ / return this.info.count*this.info.price*this.info.sale+this.info.freight / / use ES6 to write totalPrice () {return this.info.count*this.info.price*this.info.sale+this.info.freight;}}, methods: {getTotalPrice () {return this.info.count*this.info.price*this.info.sale+this.info.freight;}

Interface display effect:

From the above example, we can see that the final effect of the calculation property and the method implementation is the same. So what's the difference between calculating properties and methods? The calculated properties are cached based on their responsive dependencies and are only re-evaluated when the responsive dependencies change. This means that as long as the responsive dependency has not changed, multiple access to the evaluation property will immediately return the previous calculation result without having to perform the calculation again. By contrast, calling a method always executes the function again. The differences between the properties and methods of total price calculation are as follows:

The calculation property changes automatically when the dependency changes, while the method needs to be triggered when the dependency changes.

The evaluation property is recalculated when the dependency changes, and the method is executed each time it is called.

Look at the following example:

Calculation attribute you purchased the quantity and use the calculation attribute to get the total price: {{totalPrice}} Yuan calculate attribute to get the total price: {{data}} yuan export default {name:'ComputedDemo', data () {return {info: {userId:1 Price:15, name:' package, count:3, sale:0.8, freight:5}, data:0}} Computed: {/ / define the calculation attribute totalPrice / / totalPrice:function () {/ / return this.info.count*this.info.price*this.info.sale+this.info.freight / / use ES6 to write totalPrice () {console.log ('calculation property'); return this.info.count*this.info.price*this.info.sale+this.info.freight;}}, methods: {getTotalPrice () {console.log ('method') This.data= this.info.count*this.info.price*this.info.sale+this.info.freight;}

The "calculation property" is printed multiple times when the dependency changes, and the method does not change until the button is clicked. Click the button when the dependency does not change, and the "method" will also be printed. As shown in the following figure:

2. Calculation attribute usage scenario

If we have a computational attribute A with high performance overhead, it needs to traverse a large array and do a lot of calculations, and then we may have other computational properties that depend on the computational attribute A. If you do not use computational properties, it will inevitably be calculated multiple times, which will consume a lot of performance, in which case you need to use computational properties.

Third, modify the value of the calculation attribute

In the above example, the obtained value of the calculated property is used, so how to modify the value of the calculated property? Look at the following example:

Modify calculation property num: {{num}} calculation property num2: {{num2}} change the value of calculation property export default {name:'ComputedDemo2', data () {return {num:100}}, computed: {num2 () {return this.num-10 }}, methods: {change () {this.num2=60;}

Effect:

At this point, you will find that there is an error in directly modifying the value of the calculation property, because the value of the calculation property cannot be modified directly. If you want to modify the value of the calculation property, you need to modify the value of its dependency. See the following code:

Modify the calculation property num: {{num}} calculation property num2: {{num2}} change the value of the calculation property import {get} from 'http' Export default {name:'ComputedDemo2', data () {return {num:100}}, computed: {num2: {/ / when the calculation property is to be modified, trigger the set method / / to read the value in the current calculation property, and the get method can hide The default entry is the get method get:function () {return this.num-10 }, set:function (val) {this.num=val;}, methods: {change () {/ / calculation attribute cannot be directly modified this.num2=60;}

Effect before modification:

The effect of the modification:

Summary

The value of the calculated property cannot be modified. If you want to modify the value of the calculated property, you can modify the value of the calculated property by changing the value of its dependency through the set method in the calculated property.

IV. Monitoring attributes

The listening property (watch) is used to listen to whether the data in the data has changed, usually to listen for an attribute in the data.

More flexible and general-purpose API.

Any logic can be performed in watch, such as function throttling, Ajax getting data asynchronously, and even manipulating DOM.

1. Monitor general attributes

Look at the following code:

Monitoring attribute name: {{userName}} Age: {{age}} export default {name:'watchDemo', data () {return {userName: "abc", age:23}}, methods: {change () {}} Watch: {/ / listen for changes in userName / / there are two parameters NewValue represents the changed value, and oldValue represents the pre-changed value userName:function (newValue,oldValue) {console.log ('modified value:' + oldValue) Console.log ('modified value:' + newValue);}, / listen for changes in age age:function (newValue,oldValue) {console.log ('modified value:' + oldValue); console.log ('modified value:' + newValue);}

Interface effect:

2. The difference between monitoring attributes and computing attributes.

The main differences between snooping properties and computational properties are as follows:

The performance of computational attributes is better. A listening attribute can only listen for changes in one attribute. If you want to listen to multiple attributes at the same time, you need to write multiple listening properties, while the computational attribute can listen for changes in multiple data at the same time. The listening property can get the value of the property before the change. Computing is performance-based, and watch can do it, and vice versa. Compute attributes can be used as much as possible.

Requirements: print the current userName and age values when userName or age changes.

Use the listening property to implement:

Monitoring attribute name: {{userName}} Age: {{age}} {{info}} export default {name:'watchDemo', data () {return {userName: "abc", age:23, info:''}} Methods: {change () {}}, watch: {/ / listen for changes in userName / / there are two parameters NewValue represents the changed value, and oldValue represents the pre-changed value userName:function (newValue,oldValue) {/ / console.log ('modified value:' + oldValue) / / console.log ('modified value:' + newValue); this.info='my name:'+ this.userName+', Age:'+ this.age;}, / / listen for changes in age age:function (newValue,oldValue) {/ / console.log ('modified value:' + oldValue); / / console.log ('modified value:' + newValue) This.info='my name:'+ this.userName+', Age:'+ this.age;}

If you want to achieve the above requirements, you need to listen to both userName and age, and the code in the listening attributes is duplicated. If there are multiple listening attributes, you need to write multiple listening attributes. Looking at the calculation properties:

Monitoring attribute name: {{userName}} Age: {{age}} {{getUserInfo}} export default {name:'watchDemo', data () {return {userName: "abc", age:23, info:''}} Methods: {change () {}}, / / watch: {/ listen for changes in userName / there are two parameters NewValue represents the changed value, and oldValue represents the pre-changed value / / userName:function (newValue,oldValue) {/ console.log ('modified value:' + oldValue) / console.log ('modified value:' + newValue); / / this.info='my name:'+ this.userName+', Age:'+ this.age; / /}, / listen for changes in age / / age:function (newValue,oldValue) {/ console.log ('modified value:' + oldValue) / console.log ('modified value:' + newValue); / / this.info='my name:'+ this.userName+', Age:'+ this.age; / /} / /} computed: {getUserInfo () {return'my name:'+ this.userName+', Age:'+ this.age;}

If you use computational properties, you only need to write once to implement the above requirements.

3. Monitor complex objects

The above example shows the common properties of listening, so how do you listen to the properties in the object? Look at the following code:

Monitoring property name: {{userName}} Age: {{age}} {{getUserInfo}} listening object property name: {{obj.name}} export default {name:'watchDemo', data () {return {userName: "abc" Age:23, info:'', / / object obj: {name:'123'}}, methods: {change () {}}, watch: {/ / listen for changes in userName / / there are two parameters NewValue represents the changed value, and oldValue represents the pre-changed value userName:function (newValue,oldValue) {/ / console.log ('modified value:' + oldValue) / / console.log ('modified value:' + newValue); this.info='my name:'+ this.userName+', Age:'+ this.age;}, / / listen for changes in age age:function (newValue,oldValue) {/ / console.log ('modified value:' + oldValue); / / console.log ('modified value:' + newValue) This.info='my name:'+ this.userName+', Age:'+ this.age;}, / / listen for changes in attributes in the object 'obj.name':function (newValue,oldValue) {console.log (' pre-modified value:'+ oldValue); console.log ('modified value:' + newValue) }, computed: {getUserInfo () {return'my name:'+ this.userName+', Age:'+ this.age;}

Effect:

Can you execute the listening object? The answer is yes, look at the following code:

Monitoring attribute name: {{userName}} Age: {{age}} {{getUserInfo}} listening object property name: {{obj.name}} listening object name: {{obj.name}} export default {name:'watchDemo' Data () {return {userName: "abc", age:23, info:'', / / object obj: {name:'123'}}, methods: {change () {}} Watch: {/ / listen for changes in userName / / there are two parameters NewValue represents the changed value, and oldValue represents the pre-changed value userName:function (newValue,oldValue) {/ / console.log ('modified value:' + oldValue) / / console.log ('modified value:' + newValue); this.info='my name:'+ this.userName+', Age:'+ this.age;}, / / listen for changes in age age:function (newValue,oldValue) {/ / console.log ('modified value:' + oldValue); / / console.log ('modified value:' + newValue) This.info='my name:'+ this.userName+', Age:'+ this.age;}, / / listen for changes in attributes in the object / / 'obj.name':function (newValue,oldValue) {/ / console.log (' pre-modified value:'+ oldValue); / / console.log ('modified value:' + newValue) / / Direct listening object obj: {/ / handler represents the default function handler (newValue,oldValue) {console.log ('modified value:') console.log (oldValue); console.log ('modified value:'); console.log (newValue) }, / / indicates deep monitoring / / true: indicates that the handler function will execute / / false: indicates that the handler function will not execute deep:true}}, computed: {getUserInfo () {return'my name:'+ this.userName+', age:'+ this.age;}

Effect:

These are all the contents of this article entitled "how to use Computational and snooping Properties in Vue". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to 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