<vue 基础知识 4、计算属性computed>

代码结构

 

 

 

一、     计算属性简单使用

1、效果  

2、代码

01-计算属性简单用法.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>01-什么是计算属性</title>
</head>
<body>

<div id="app">
  <h2>{{firstName}} {{lastName}}</h2>
  <h2>{{fullName}}</h2>
</div>

<script src="vue.js"></script>
<script>
  let app = new Vue({
    el: '#app',
    data: {
      firstName: '张',
      lastName : '三'
    },
    computed: {
      fullName() {
        return this.firstName + ' ' + this.lastName
      }
    }
  })
</script>

</body>
</html>

 

一、     计算属性复杂使用

1、 效果

计算多本书的总价

 

2、代码

02-绑定class属性.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>02-计算属性复杂操作</title>
</head>
<body>

<div id="app">
  <h2>总价值: {{totalPrice}}</h2>
</div>

<script src="vue.js"></script>
<script>
  let app = new Vue({
    el: '#app',
    data: {
      books: [
        {name: '三国演义', price: 100, count: 1},
        {name: '西游记',  price: 90, count: 2},
        {name: '红楼梦',  price: 80, count: 3},
      ]
    },
    computed: {
      totalPrice() {
        let total = 0
        for (let i in this.books) {
			let book = this.books[i]
			total += book.price * book.count
        }
        return total
      }
    }
  })
</script>

</body>
</html>

 

三、computed和methods的区别

1、效果

computed 与methods 的方法区别

(1)     调用的时候computed不用加括号

(2)     computed会对计算结果进行缓存而methods不会

2、 代码

03-绑定class属性(综合练习).html

<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8">
		<title>03-computed和methods的区别</title>
	</head>
	<body>

		<div id="app">
			<h2>{{fullName}}</h2>
			<h2>{{fullName}}</h2>
		 
			<h2>{{getFullName()}}</h2>
			<h2>{{getFullName()}}</h2>
 
		</div>

		<script src="vue.js"></script>
		<script>
			let app = new Vue({
				el: '#app',
				data: {
					firstName: '张',
					lastName: '三'
				},
				computed: {
					fullName() {
						console.log('调用了computed中的fullName');
						return this.firstName + ' ' + this.lastName
					}
				},
				methods: {
					getFullName() {
						console.log('调用了methods中的getFullName');
						return this.firstName + ' ' + this.lastName
					}
				}
			})
		</script>

	</body>
</html>

 

posted @ 2021-11-16 15:42  万笑佛  阅读(40)  评论(0编辑  收藏  举报