基本示例:
示例1:计算属性基本操作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算属性的基本使用</title>
</head>
<body>
<div id="app">
<h2>{{firstName}}</h2>
<h2>{{lastName}}</h2>
<h2>{{fullName}}</h2>
</div>
</body>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
firstName: 'ten',
lastName: 'cent'
},
computed: {
fullName: function () {
return this.firstName + this.lastName
}
}
})
</script>
</html>
示例2:计算属性复杂操作
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算属性的复杂操作</title>
</head>
<body>
<div id="app">
<h2>总价格:{{totalPrice}}</h2>
</div>
</body>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
books: [
{id: 1, name: 'unix编程艺术', price: 102},
{id: 2, name: 'linux操作指南', price: 123},
{id: 3, name: 'web编程艺术', price: 155},
{id: 4, name: 'dom操作指导', price: 178},
]
},
computed: {
totalPrice: function () {
let result = 0
for (const book of this.books) {
result += book.price
}
return result
}
}
})
</script>
</html>
计算属性的getter和setter:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算属性的getter和setter</title>
</head>
<body>
<div id="app">
<h2>{{firstName}}</h2>
<h2>{{lastName}}</h2>
<h2>{{fullName}}</h2>
<h2>{{fullName2}}</h2>
</div>
</body>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
firstName: '火影',
lastName: '忍者'
},
computed: {
fullName: function () {
return this.firstName + this.lastName
},
// 计算属性一般是没有set方法的,只读属性
fullName2: {
get: function () {
return this.firstName + this.lastName
},
set: function () {
}
}
}
})
</script>
</html>
计算属性和method的区别:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算属性和method的区别</title>
</head>
<body>
<div id="app">
<h2>{{getFullName()}}</h2>
<h2>{{getFullName()}}</h2>
<h2>{{getFullName()}}</h2>
<h2>{{getFullName()}}</h2>
<br>
<h2>{{fullName}}</h2>
<h2>{{fullName}}</h2>
<h2>{{fullName}}</h2>
<h2>{{fullName}}</h2>
<button @click="changeName">修改firstName</button>
</div>
</body>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
firstName: '火影',
lastName: '忍者'
},
computed: {
fullName: function () {
console.log('fullName');
return this.firstName + this.lastName
}
},
methods: {
getFullName: function () {
console.log('getFullName');
return this.firstName + this.lastName
},
changeName: function () {
this.firstName = '假'
}
}
})
</script>
</html>
结果:
可以看见computed只调用了一次,method调用了四次,这是因为computed对字段做了一层缓存