当前位置: 首页 > article >正文

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)
},

http://www.kler.cn/a/297473.html

相关文章:

  • AI工具(不断更新)
  • RTOS实时操作系统(任务运行性能分析)
  • 使用jenkins 打包前端私服代码失败的问题
  • A Comprehensive Survey on Graph Neural Networks笔记
  • 【Python 千题 —— 算法篇】字符串替换
  • 编译win2k3简易教程(202409)
  • 紫色UI趣味测试小程序源码,包含多种评测
  • vue3实现拖拽移动位置,拖拽过程中鼠标松开后元素还吸附在鼠标上并随着鼠标移动
  • 2409wtl,wtl与ddx
  • 服务器监控工具都是监控服务器的哪些性能和指标
  • 【文心智能体】通过工作流使用知识库来实现信息查询输出,一键查看旅游相关信息,让出行多一份信心
  • 【重学 MySQL】五、MySQL 的卸载
  • 数据结构:图
  • kubernetes集群部署Confluence 7.2.0+mysql 5.7(自测有效)
  • 【MySQL】—— MySQL命令行客户端介绍
  • 【Python知识宝库】Python中的日期和时间处理:datetime模块详解
  • FPGA随记——OSERDESE2和IERDESE2
  • 论文风向变了!迁移学习+多模态融合才是王道!性能爆炸好
  • TCP Analysis Flags 之 TCP Port numbers reused
  • 用 Python 创建一个简单的速算挑战游戏