computed 用于定义计算属性,
计算属性不需要参数,数据来源于this
<body><script src='https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js'></script><div id='myApp'><h3>购物车商品总价</h3><ol><li>使用自定义函数计算: {{myPrice1(shopCar)}}</li><li>使用过滤器计算: {{shopCar | myPrice2}}</li><li>使用计算属性计算: {{myPrice3}} </li><li>计算属性的用法和data中的字段一样, 区别是: data中的字段是可读可写的, 而计算属性是只读的,不能直接手动修改, 只能通过修改data中的数据源使计算属性更新 </li><li>计算属性和过滤器/自定义函数的最大区别是: 计算属性调用多次不会重复计算,只会计算一次, 更节省性能消耗, 只有和它相关的数据源变化时才会重新计算结果</li><li>{{myPrice1(shopCar)}}-{{myPrice1(shopCar)}}-{{myPrice1(shopCar)}}-{{shopCar | myPrice2}}-{{shopCar | myPrice2}}-{{shopCar | myPrice2}}-{{myPrice3}}-{{myPrice3}}-{{myPrice3}}</li></ol></div><script>new Vue({el: '#myApp',data: {shopCar: [{name:'iphone13', price: 5999, count: 2},{name:'袜子', price: 3, count: 30},{name:'屏幕抹布', price: 149, count: 5}]},// computed 用于定义计算属性,computed:{// 计算属性不需要参数,数据来源于thismyPrice3(){console.log("myPrice3")var all = 0this.shopCar.forEach(item => {all += item.price * item.count;});return all;}},filters:{myPrice2(carList){console.log("myPrice2")var all = 0carList.forEach(item => {all += item.price * item.count;});return all;}},methods: {myPrice1(carList){console.log("myPrice1")var all = 0carList.forEach(item => {all += item.price * item.count;});return all;}},created() {console.log(this.shopCar, this.myPrice3);setTimeout(() => {this.shopCar[0].count = 1;}, 1000);},})</script></body>
