什么是计算属性
计算属性的基本操作
<div id="app">
<h2>{{first+' '+last}}</h2>
<h2>{{first}} {{last}}</h2>
<h2>{{getTwo()}}</h2>
<!-- 计算属性 -->
<h2>{{mergeTwo}}</h2>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
first:'one',
last:'two'
},
// 计算属性
computed:{
// mergeTwo本质是一个属性
mergeTwo:function(){
return this.first+' '+this.last
}
},
methods: {
getTwo(){
return this.first+' '+this.last
}
}
});
</script>
计算属性的get和set
<body>
<div id="app">
<h2>{{fullName}}</h2>
</div>
<script>
var vm = new Vue({
el: '#app',
data: {
firstName:'zhangsan',
lastName:'lisi'
},
computed: {
// 属性对象 一般情况下只需要实现的是get方法,下面有更简洁的写法
fullName: {
// set一般需要传参
set:function(newValue){
// console.fullName(newValue)
const name = newValue.split(' ')
this.firstName = name[0]
this.lastName = name[1]
},
get:function(){
return this.firstName + ' ' + this.lastName
}
}
// 所以可以简写成
// fullName:function(){
// return this.firstName + ' ' + this.lastName
// }
},
methods: {}
});
</script>
计算属性的缓存,和methods的区别
计算属性相对于methods方法不仅简化了编码,而且也具有更高的性能,用method方法如果需要多次使用的话它就会被多次调用,但是计算属性会被缓存,只会调用一次。