computed计算属性跟method的主要区别就是computed具备缓存特性,可以提升性能
,计算属性会对计算出来的结果进行缓存,再次使用该数据时可以直接从缓存中读取,如果依赖的数据发生改变时,计算属性会自动重新计算并再次缓存。
计算图书总数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<body>
<div id="app">
<ul>
<li v-for="(item,index) in list">
{{item.name}} {{item.num}}
</li>
</ul>
<p>总计:{{totalNum}}</p>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
list: [
{ id: 1, name: '《红楼梦》', num: 100 },
{ id: 2, name: '《三国》', num: 200 }
]
},
computed: {
totalNum() {
return this.list.reduce((sum, item) => (sum + item.num), 0)
}
}
})
</script>
</body>
</html>
这种计算属性写法是默认写法,但是只能读取属性,并不提供修改属性的方法
computed: {
totalNum() {
return this.list.reduce((sum, item) => (sum + item.num), 0)
}
}
改名案例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<body>
<div id="app">
<input v-model="firstName"> + <input v-model="lastName"> = <input v-model="fullName">
<button @click="changeName">改名卡</button>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
firstName: '张',
lastName: '飞'
},
computed: {
fullName() {
return this.firstName + this.lastName;
}
},
methods: {
changeName() {
this.fullName = "吕布"
}
}
})
</script>
</body>
</html>
这种方式修改fullName
时就会报下面这个异常,表示fullName
这个计算属性没有更改的方法。
vue.js:5110 [Vue warn]: Computed property "fullName" was assigned to but it has no setter.
将上面案例的computed
修改成下面这样:
computed: {
fullName: {
get() {
return this.firstName + this.lastName;
},
set(value) {
this.firstName = value.slice(0, 1)
this.lastName = value.slice(1)
}
}
}