计算属性:优先推荐,原因:既简洁又性能高
<body>
<div id="app">
{{fullName}}
{{age}}
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
firstName: 'hello',
lastName: 'world',
age: 28
},
// 计算属性
computed: {
fullName: function() {
console.log("计算了一次");
return this.firstName + " " + this.lastName;
}
}
})
</script>
<body>
方法
<body>
<div id="app">
{{fullName()}}
{{age}}
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
firstName: 'hello',
lastName: 'world',
age: 28
},
methods: {
fullName: function() {
console.log("计算了一次");
return this.firstName + " " + this.lastName;
}
}
})
</script>
<body>
侦听器
<body>
<div id="app">
{{fullName}}
{{age}}
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
firstName: 'hello',
lastName: 'world',
fullName: 'hello world',
age: 28
},
watch: {
firstName: function() {
console.log("计算了一次");
this.fullName = this.firstName + " " + this.lastName;
},
lastName: function() {
console.log("计算了一次");
this.fullName = this.firstName + " " + this.lastName;
}
}
})
</script>
<body>
计算属性的 getter 和 setter
<body>
<div id="app">
{{fullName}}
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
firstName: 'hello',
lastName: 'world',
},
// 计算属性
computed: {
fullName: {
get: function() {
console.log("计算了一次");
return this.firstName + " " + this.lastName;
}
set: function(value) {
var arr = value.split(" ");
this.firstName = arr[0];
this.lastName = arr[1];
}
}
}
})
</script>
<body>