<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script src="../vue.js"></script> <div id="app"> <h2>{{fir+last}}</h2> <h2>{{fir}}{{last}}</h2> <h2>{{getFull()}}</h2> <h2>{{fullname}}</h2> <!--计算属性不能加小括号--> </div> <script> const vm = new Vue({ el : '#app', data:{ fir:'Lose', last:'James', }, //计算属性,是属性不是方法 computed:{ fullname:function () { return this.fir+this.last; } }, methods:{ getFull(){ return this.fir+this.last; } } }) </script> </body> </html>
计算属性的复杂操作
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script src="../vue.js"></script> <div id="app"> <h2>{{fir+last}}</h2> <h2>{{fir}}{{last}}</h2> <h2>{{getFull()}}</h2> <h2>{{fullname}}</h2> </div> <script> const vm = new Vue({ el : '#app', data:{ books:[ {id:'11',name:'Unix编程艺术',price:100}, {id:'12',name:'代码大全',price:100}, {id:'101',name:'深入理解计算机原理',price:100}, {id:'113',name:'现代操作系统 ',price:100}, {id:'112',name:'构建之法',price:100}, ] }, computed:{ totalprice:function () { let result=0; for(let i=0;i<this.book.length;i++){ result=this.book[i].price } } } }) </script> </body> </html>
计算属性的getter与setter
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script src="../vue.js"></script> <div id="app"> {{fullName}} </div> <script> const app =new Vue({ el:'#app', data:{ fir:'fvsd', last:'sdsv', }, computed:{ //只是简写 //fullName:function () { // return this.fir+this.last //} // name:'dscc' //计算属性的完整写法 //计算属性一般没有set方法,只读属性 //fullNamse就是一个属性 fullName:{//是一个对象 set:function (newValue) { console.log('---','newValue') const names=newValue.split(' ') this.fir=names[0] this.last=names[1] }, get:function () { return this.fir+this.last } } } }) </script> </body> </html>