Vue学习------------(5)计算属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<h2>{{firstName}} {{lastName}}</h2>
<h2>{{firstName + ' ' + lastName}}</h2>
<h2>{{fullName}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
const app=new Vue({
el : '#app',
data : {
firstName: 'Lebron' ,
lastName: 'James'
},
computed: {
fullName: function (){
return this.firstName+' '+this.lastName
}
}
})
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<h2>总价格:{{totalPrice}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
const app=new Vue({
el : '#app',
data : {
books: [
{id: 1, name: 'Unix编程艺术', price: 110},
{id: 2, name: '代码大全', price: 117},
{id: 3, name: '深入理解计算机系统', price: 98},
{id: 4, name: '现代操作系统', price: 88}
]
},
computed: {
totalPrice: function (){
let result = 0
for(let i=0;i<this.books.length;i++){
result+=this.books[i].price
}
return result
}
}
})
</script>
</body>
</html>
计算属性setter(不常用)和getter:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<h2>{{fullName}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
const app=new Vue({
el : '#app',
data : {
firstName: 'kobe',
lastName: 'bryant'
},
computed: {
fullName: {
set: function (){
},
get: function (){
return this.firstName + ' ' + this.lastName
}
}
}
})
</script>
</body>
</html>
浙公网安备 33010602011771号