一、计算属性
计算属性中定义的值可以直接绑定在表达式中。如果某些值需要通过计算才能得到,那使用计算属性就再合适不过了。
1 <template> 2 <div> 3 <h1>{{fullTitle}}</h1> 4 <h2>{{title}}</h2> 5 </div> 6 </template> 7 8 export default { 9 data(){ 10 return { 11 title:"hello world" 12 } 13 }, 14 computed:{ 15 fullTitle(){ 16 return "融职教育-" + this.title 17 } 18 } 19 }
在上面的示例代码中fullTitle
的值是通过title
属性计算而来,所以可以通过computed
获得计算的结果,并绑定到表达式中。
但是这个例子并没有说服力,我们还可以用很多其他方法来实现这个功能,那我们再来制作一个计数器效果,让computed
属性发挥它的作用。
1 <template> 2 <div id="app"> 3 <div>单价{{price}}</div> 4 <div> 5 <button @click="sub">-</button> 6 <span>{{count}}</span> 7 <button @click="add">+</button> 8 </div> 9 <div>总价:{{totalPrice}}</div> 10 </div> 11 </template>
我们在之前的实例中,在data属性中定义了三个变量:price、count、totalPrice。
利用计算属性可以简化这个示例:
1 export default { 2 name: 'app', 3 data(){ 4 return { 5 name:"xiaoming", 6 count:0, 7 price:15 8 } 9 }, 10 computed:{ 11 totalPrice(){ 12 return this.count * this.price 13 } 14 }, 15 methods:{ 16 add(){ 17 this.count++ 18 }, 19 sub(){ 20 this.count-- 21 } 22 } 23 }
二、侦听属性
侦听属性可以实时监控一个属性的变化,如果这个值发生变化了,可以执行某些操作,我们用侦听器来改写上面的计数器功能,示例代码如下所示
1 export default { 2 name: 'app', 3 data(){ 4 return { 5 name:"xiaoming", 6 count:0, 7 price:15 8 } 9 }, 10 watch:{ 11 count(newValue,oldValue){ 12 console.log(newValue) 13 console.log(oldValue) 14 this.totalPrice = newValue * this.price 15 }, 16 }, 17 methods:{ 18 add(){ 19 this.count++ 20 }, 21 sub(){ 22 this.count-- 23 } 24 } 25 }
三、计算属性与侦听属性对比
如果关注的是一个变量的结果,使用计算属性;如果关注一个变量的改变会导致一系列行为,使用侦听属性。
四、课后练习
使用表格制作一个购物清单,商品列表数据如下
1 [ 2 {"name":"香蕉","price":3.14}, 3 {"name":"苹果","price":2.25}, 4 {"name":"鸭梨","price":6} 5 ]
功能如下所示
- 通过计数器选择购物清单数量
- 根据数量和单价计算总价