1.计算属性在{{ }}语法里调用可不用加括号,取名字按照属性来。
2.计算属性获取数据,必须有返回值。set方法有参数在属性里面的方法
3.多次使用只会调用一次,自带缓存。比方法效率高(多使用)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<h1>get方法测试:{{fullName}}</h1>
<h1>set| get方法测试:{{name}}</h1>
<h2>计算属性|总年龄:{{sumAge}}</h2>
</div>
</body>
<script>
const app = new Vue({
el: '#app',
data: {
user: 'liyongbo',
age: 18,
users: [
{id: 100, name: '小ming', age: 12},
{id: 101, name: '小li', age: 13},
{id: 102, name: '小yun', age: 14},
{id: 103, name: '小gao', age: 15}
]
},
computed: {
// 默认get方法
fullName: function () {
return this.user + this.age
},
// name 计算属性的set get 方法。set方法接收一个输入参数
name: {
set: function (newUser) {
const name = newUser.split('|');
this.user = name[0];
this.age = name[1];
},
get: function () {
return this.user + this.age
}
},
sumAge: function () {
let age = 0
for (let i = 0; i < this.users.length; i++) {
age += this.users[i].age
}
return age;
}
},
methods: {}
})
</script>
</html>
计算属性set()方法修改,往方法中传一个参数