Vue官网学习(计算属性和侦听器:一、计算属性)

模板内的表达式非常便利,但是设计它们的初衷是用于简单运算的。在模板中放入太多的逻辑会让模板过重且难以维护。例如:

<div id="example">
  {{ message.split('').reverse().join('') }}
</div>

所以,对于有着复杂的计算并且复用性高的,这种情况下,我们应该使用计算属性:
下面举个例子说明:(有ES6的语法,不懂的可以去看看ES6的语法)

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>计算属性</title>
	</head>
	<body>
		<div id="app">
			<div>全名: {{fullName}}</div>
			<div>总分数为 :{{totalScores}}</div>
			<div>平均分 :{{avgScores}}</div>
			<div>最高分 :{{maxScores}}</div>
			<div>最低分 :{{minScores}}</div>
		</div>
	</body>
	<script src="../js/vue.min.js"></script>
	<script>
		new Vue({
			el: '#app',
			data: {
				firstName: "zanmu",
				lastName: 'si',
				students: [
					{id: 1, scores: 56},
					{id: 2, scores: 86},
					{id: 3, scores: 70},
					{id: 4, scores: 90},
					{id: 5, scores: 60},
					{id: 6, scores: 78},
					{id: 7, scores: 87},
					{id: 8, scores: 76}
				]
			},
			computed: {
				fullName(){
					return this.lastName + " " + this.firstName
				},
				totalScores(){
					return this.students.reduce((totalScores, curr) => {
							return totalScores + curr.scores
					},0)
				},
				avgScores(){
					return (this.totalScores/this.students.length).toFixed(2)
				},
				maxScores(){
					let arr = this.getSortList;
					return arr[0].scores;
				},
				minScores(){
					let arr = this.getSortList;
					return arr[arr.length-1].scores;
				},
				getSortList(){
					return this.students.sort((item1, item2) => {
						return item2.scores - item1.scores
					})
				}
			}
		});
	</script>
</html>

最后的结果就是:

全名: si zanmu
总分数为 :603
平均分 :75.38
最高分 :90
最低分 :56

猜你喜欢

转载自blog.csdn.net/qq_42154259/article/details/106942218
今日推荐