相比于methods,computed仅在数据改变时才会调用,能够提高性能。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id='app'>
{{fullName}}
{{age}}
</div>
</body>
<script src="./js/vue.min.js"></script>
<script>
var vm = new Vue({
el:'#app',
data:{
firstName:'Mona',
LastName:'Lee',
age:'15'
},
//仅数据改变才重新调用,提高性能
computed:{
fullName:{
//使用fullName就是调用get
get: function(){
console.log('get call!');
return this.firstName+' '+this.LastName
},
//fullName改变时触发
set: function(value){
console.log('set call!');
this.firstName = value.split(' ')[0];
this.LastName = value.split(' ')[1];
}
}
},
// watch:{
// firstName:function(){
// this.fullName = this.firstName+' '+this.LastName;
// },
// LastName:function(){
// this.fullName = this.firstName+' '+this.LastName;
// }
// }
});
</script>
</html>