Vue学习:计算属性Computed

计算属性可以实时监听 data节点中数据的变化,并 return 一个计算后的新值,供组件渲染 DOM 时使用,计算属性需要以 function 函数的形式声明到组件的 computed 节点中。

计算属性的使用注意点:

(1)计算属性必须定义在 computed 节点中
(2)计算属性必须是一个 function 函数
(3)计算属性必须有返回值
(4)计算属性必须当做普通属性使用

计算属性computed VS 方法methods

相对于方法(methods)来说,计算属性会缓存计算的结果,只有计算属性的依赖项发生变化时,才会重新进行运算,因此计算属性的性能更好。下面案例很好的说明了这一点。

<!DOCTYPE html>
<html>
    <head>
        <title>computed 应用示例</title>
         <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    </head>
    <body>
        <div id="app"> 
          <p>count的值是{{count}},乘2后是{{mul}}</p>  
          <p>count的值是{{count}},乘2后是{{mul}}</p>        
          <p>count的值是{{count}},乘2后是{{mul}}</p>        
          <p>sum的值是{{sum}},乘2后是{{mul2()}}</p>    
          <p>sum的值是{{sum}},乘2后是{{mul2()}}</p>        
          <p>sum的值是{{sum}},乘2后是{{mul2()}}</p>        
        </div>    
    </body>
    <script type="text/javascript">
        const RootComponent = {       //创建根组件
            data () {
                return {
                    count:5,
                    sum:10,
                }      
            },
            computed:{              //计算属性
             mul(){
                console.log('计算属性被执行了');
                return this.count*2
             }
            } ,   
            methods:{               //方法选项
                mul2(){
                    console.log('方法被执行了');
                    return this.sum * 2
                }
            }       
        }         
        const vueApp = Vue.createApp(RootComponent)    //创建Vue应用实例 
        vueApp.mount("#app")       //挂载处理       
    </script>    

</html>

从console控制台执行结果可以看出,computed计算属性被执行了1次,methods方法被执行了3次。
在这里插入图片描述

计算属性案例-图书总价格

在这里插入图片描述
代码如下:

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<meta http-equiv="X-UA-Compatible" content="IE=edge">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
		<title>计算属性案例-图书总价格</title>
		<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
	</head>
	<body>
		<div id='app'>
			<table>
				<thead>
					<tr>
					<th>Id</th>
					<th>书名</th>
					<th>封面</th>
					<th>价格</th>
					</tr>
				</thead>
				<tbody>
					<tr v-for="item in books" :key="item.id">
						<td>{{ item.id }}</td>
						<td>{{ item.name }}</td>
						<td><img :src="item.pic" alt=""></td>
						<td>{{ item.price.toFixed(2) }}</td>
					</tr>
				</tbody>
				<tfoot>
				<tr>	<th></th><th></th><th>图书总价格:</th><th>{{totalPrice}}</th></tr>
				</tfoot>
			</table>
		</div>
		<script>
			var vm = {
				data() {
					return {
						books: [{
								id: 1001,
								name: '啊哈!算法',
								pic:'./images/aha.jpg',
								price: 59.80,
							},

							{
								id: 1002,
								name: '人工智能(第2版)',
								pic:'./images/AI.jpg',
								price: 108.00
							},
							{
								id: 1003,
								name: 'JavaScriptDOM编程艺术',
								pic:'./images/jscript.jpg',
								price: 49.00
							},
							{
								id: 1004,
								name: ' Python基础教程',
								pic:'./images/python.jpg',
								price: 79.00
							},
						]
					}
				},
				computed: {
					totalPrice() {
						let total = 0;
						for (let item of this.books) {
							total += item.price
						}
						return total.toFixed(2)
					},
				},
			}
			const vueApp = Vue.createApp(vm)
			vueApp.mount('#app')
		</script>
	<style>
		td,th{
			padding: 10px 20px;
			text-align: center;
		}
		td img{
			width: 80px;
		}
	</style>
	</body>
</html>

totalPrice() 的另一种常规写法

totalPrice() {
	let total = 0;
	for (let i = 0; i < this.books.length; i++) {
		total += this.books[i].price;
	}
	return total.toFixed(2)
},
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值