1、使用场景
用于处理不能直接展示在前端的数据
2、和method的区别
computed有缓存,如果data里面的数据不改变,就直接读取缓存,不会多次执行消耗性能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="../js/vue.js"></script>
<div id="app">
<span>{{totalPrice}}</span>
<span>{{totalPrice}}</span>
<span>{{totalPrice}}</span>
<span>{{totalPrice}}</span>
<span>{{getTotalPrice()}}</span>
<span>{{getTotalPrice()}}</span>
<span>{{getTotalPrice()}}</span>
<span>{{getTotalPrice()}}</span>
</div>
<script>
const app = new Vue({
el: "#app",
data: {
books:[
{name: 'B1', price: 56},
{name: 'B2', price: 45},
{name: 'B3', price: 73},
{name: 'B4', price: 25}
]
},
computed: {
totalPrice() {
console.log('进入了computed')
let price = 0
for (index in this.books) {
price += this.books[index].price
}
return price
}
},
methods: {
getTotalPrice: function() {
console.log('进入了方法')
let price = 0
for (book in this.books) {
price += book.price
}
return price
}
}
})
</script>
</body>
</html>
会发现方法执行了多次,computed执行了一次
3、set方法
默认computed只是有get方法,也可以定义一个对象,包含两个key,一个是set,一个是get
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script src="../js/vue.js"></script>
<div id="app">{{message}}
<span>firstName: {{firstName}}</span>
<span>lastName: {{lastName}}</span>
<span>全名:{{fullName}}</span>
<button @click="setTestData()">改变</button>
</div>
<script>
const app = new Vue({
el: "#app",
data: {
message: '你好啊',
firstName: 'Cheng',
lastName: 'Vivien'
},
methods: {
setTestData() {
this.fullName = 'hello beier'
}
},
computed: {
fullName: {
get () {
return this.firstName + ' ' + this.lastName
},
set(val) {
let names = val.split(' ')
this.firstName = names[0]
this.lastName = names[1]
}
}
}
})
</script>
</body>
</html>