9.Vue计算属性
9.1计算属性基本使用
-
在某些情况,我们可能需要对数据进行一些转化后再显示,或者需要将多个数据结合起来进行显示
<script src="../js/vue.js"></script> <div id="app"><!--显示声明--> <!--简单重复语句给人不美观感觉--> <h2>{{message+' '+liatname}}</h2> <h2>{{message}} {{liatname}}</h2> <h2>{{getfullName()}}</h2> <!--使用计算属性进行拼接--> <h2>{{fullName}}</h2> </div> <script> const app =new Vue({ el:'#app',//用于挂载有管理的元素 data:{//定义数据 message:'你好',//声明变量 liatname:'jeke' }, computed:{ fullName:function (){ return this.message+' '+this.liatname } }, methods:{ getfullName:function (){ return this.message+' '+this.liatname } } }) </script>
9.2 计算属性复杂操作
- 高阶函数
- filter
- map
- reduce
9.2.1 任务:计算总价格
<script src="../js/vue.js"></script>
<div id="app"><!--显示声明-->
<h2>实现计算总价 {{totalPrice}}</h2>
</div>
<script>
const app =new Vue({
el:'#app',//用于挂载有管理的元素
data:{//定义数据
message:[
{id:100,name:"c++",count:159},
{id:101,name:"现代操作系统",count:89},
{id:100,name:"编程艺术",count:200},
{id:100,name:"Vue程序设计",count:99},
]
},
computed:{
totalPrice:function (){
let counts=0;
for (let i=0;i<this.message.length;i++){
counts+=this.message[i].count
}
return counts =this.message.length;
}
}
})
</script>
9.3计算属性Set与Get
-
完整的计算属性有SET,GET方法
-
一般不用SET
<script src="../js/vue.js"></script> <div id="app"><!--显示声明--> {{fullName}} </div> <script> const app =new Vue({ el:'#app',//用于挂载有管理的元素 data:{//定义数据 message:'kotse',//声明变量 liname:'joren' }, computed:{ /*创建的是一个属性并非是一个方法*/ fullName:{ /*完整的计算属性*/ set:function (newValue/*需要将值传输过来*/){ console.log('打印控制台',newValue); /*控制台修改app.fullName*/ /*使用split进行分割*/ const names=newValue.split(' '); /*重新注入*/ this.message=names[0]; this.liname=names[1]; }, /*一般不使用set方法因为不想被其他人修改*/ get:function (){ return this.message+" "+this.liname } }, /*简写式*/ /*一般不用set将它省略 之后将get标签省略 同时也禁止写入*/ /*get:function (){ return this.message+" "+this.liname }*/ fullNames:function (){ return this.message+" "+this.liname } } }) </script>
9.4计算属性与methods对比
-
methods:会多次调用,没有缓存,增大任务量
-
computed:调用一次,拥有缓存,更改时重新调用
<script src="../js/vue.js"></script> <div id="app"><!--显示声明--> <h2> {{fullName}}</h2> <h2> {{fullName}}</h2> <h2> {{fullName}}</h2> <h2> {{fullName}}</h2> <h2>----------</h2> <h2> {{getfullName()}}</h2> <h2> {{getfullName()}}</h2> <h2> {{getfullName()}}</h2> <h2> {{getfullName()}}</h2> </div> <script> const app =new Vue({ el:'#app',//用于挂载有管理的元素 data:{//定义数据 message:'kotse',//声明变量 liname:'joren' }, methods:{ getfullName:function (){ console.log('getfullName');/*控制台打印多次*/ return this.message+" "+this.liname } }, computed:{ fullName:function (){ /*当控制台app.message='Tonmo'会重新运行一次*/ console.log('fullName');/*控制台打印一次*/ return this.message+" "+this.liname } } }) </script>