03. Computed Attributes
November 11, 2023About 1 min
Characteristics
- 计算属性存在缓存,因此相比方法,其效率更高
- 计算属性在参与计算值不发生变化情况下,直接调用缓存结果(只计算一次)
Usuages
Basic
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="../js/vue.js"></script>
</head>
<body>
<div id="app">
<h2> {{firstName + " " + lastName}}</h2>
<h2> {{firstName}} {{lastName}}</h2>
<h2> {{ getName() }}</h2>
<h2> {{ fullName }}</h2>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
firstName: 'xxxx',
lastName: 'aaaa'
},
methods: {
getName: function(){
return this.firstName + " " + this.lastName
}
},
computed: {
fullName: function(){
return this.firstName + " " + this.lastName
}
}
})
</script>
</body>
</html>
Complex
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="../js/vue.js"></script>
</head>
<body>
<div id="app">
<h2> {{firstName + " " + lastName}}</h2>
<h2> {{firstName}} {{lastName}}</h2>
<h2> {{ getName() }}</h2>
<h2> {{ fullName }}</h2>
<h2> 总价格: {{total_price}}</h2>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
firstName: 'xxxx',
lastName: 'aaaa',
books: [
{id: 110, name: 'Unix', price: 119},
{id: 111, name: 'Unix深入理解', price: 105},
{id: 112, name: '操作系统', price: 112},
{id: 113, name: '代码大全', price: 113},
]
},
methods: {
getName: function(){
return this.firstName + " " + this.lastName
}
},
computed: {
fullName: function(){
return this.firstName + " " + this.lastName
},
total_price: function(){
let ret = 0;
for(let book of this.books){
ret += book.price;
}
return ret;
}
}
})
</script>
</body>
</html>
setter&getter
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<script src="../js/vue.js"></script>
</head>
<body>
<div id="app">
<h2> {{firstName + " " + lastName}}</h2>
<h2> {{firstName}} {{lastName}}</h2>
<h2> {{ getName() }}</h2>
<h2> {{ fullName }}</h2>
<h2> 总价格: {{total_price}}</h2>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
firstName: 'xxxx',
lastName: 'aaaa',
books: [
{id: 110, name: 'Unix', price: 119},
{id: 111, name: 'Unix深入理解', price: 105},
{id: 112, name: '操作系统', price: 112},
{id: 113, name: '代码大全', price: 113},
]
},
methods: {
getName: function(){
return this.firstName + " " + this.lastName
}
},
computed: {
fullName: {
//normally the function of setter is not needed
set: function(newValue){
console.log(newValue)
},
get: function(){
return this.firstName + " " + this.lastName
}
},
total_price: function(){
let ret = 0;
for(let book of this.books){
ret += book.price;
}
return ret;
}
}
})
</script>
</body>
</html>