Home > Article > Web Front-end > About the usage of calculated properties in Vue (with code)
This article introduces to you the usage of calculated properties in Vue (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Computed properties are a very interesting thing, where you can operate the data model, and you can also use getter and setter methods. It is also very concise and clear to use
Write an example here
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> <!--<script src="js/vue.min.js"></script>--> <script src="vue.min.js"></script> </head> <body> <div id="app"> 总价:{{prices}} </div> <script> var app=new Vue({ el:'#app', data:{ package1:[ { name:'iPhone 7', price:7199, count:2 }, { name:'iPad', price:2888, count:1 } ], package2:[ { name:'apple', price:3, count:5 }, { name:'Banana', price:2, count:10 } ]}, computed:{ prices:function () { var prices=0; for(var i=0;i<this.package1.length;i++){ prices+=this.package1[i].price*this.package1[i].count; } for (var i=0;i<this.package2.length;i++){ prices+=this.package2[i].price*this.package2[i].count; } return prices; } } }) </script> </body> </html>
Define a method to calculate price in the computed attribute, and then use the data Operate the things inside
Let’s take a look at the running results:
Then let’s take a look at how to use the getter and setter methods:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> <script src="js/vue.js"></script> </head> <body> <div id="app"> 姓名:{{fullname}} </div> <script> var app=new Vue({ el:'#app', data:{ firstName:'Jack', lastName:'Green' }, computed:{ fullname:{ //getter,用于读取 get:function () { return this.firstName+ ' '+this.lastName; }, //setter set:function (newValue) { var names=newValue.split(' '); this.firstName=names[0]; this.lastName=names[names.length-1]; } } } }) </script> </body> </html>
The effect shown is like this
is also a relatively simple usage. There are also financial calculations in the shopping model. This attribute should be used more in applications
Recommended related articles:
How to convert vue.js images to Base64, upload images and preview
## How to define global variables and global methods in #vue? (Code)
The above is the detailed content of About the usage of calculated properties in Vue (with code). For more information, please follow other related articles on the PHP Chinese website!