计算属性的setter和getter操作
<!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>
<body>
<div id="app">{{fullname}}</div>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
lastname: "SF",
firstname: "L"
},
computed: {
fullname: {
// 计算属性一般只有get属性只读属性
set: function(newvalue){
const name = newvalue.split(" ")
this.firstname = name[0]
this.lastname = name[1]
},
get: function(){
return this.firstname + " " + this.lastname
}
}
}
})
</script>
</body>
</html>
计算属性的基本操作:
<!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>
<body>
<div id="app">
<h1>{{getfullName1()}}</h1>
<h1>{{getfullName2()}}</h1>
<h1>{{fullName}}</h1>
</div>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
lastname: "SF",
firstname: "L"
},
computed: {
fullName: function(){
return this.firstname + " " + this.lastname
}
},
methods: {
getfullName1: function(){
return this.firstname + " " + this.lastname
},
getfullName2(){
return this.firstname + " " + this.lastname
}
},
})
</script>
</body>
</html>
计算属性的复杂操作:
<!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>
<body>
<div id="app">总价格:{{totalPrice}}</div>
<script src="../vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
books: [
{id: 1, name: "Unix编译艺术", price: 110},
{id: 2, name: "代码大全", price: 105},
{id: 3, name: "深入理解计算机原理", price: 85},
{id: 4, name: "现代操作系统", price: 90}
]
},
computed: {
totalPrice: function(){
let res = 0
for(let i = 0; i < this.books.length; i++){
res += this.books[i].price
}
return res
}
}
})
</script>
</body>
</html>