3.计算属性
计算属性更像一个属性,在声明的时候像方法;在使用的时候像属性。
实例:
<body>
<div id="app">
<p>{{message}}</p>
<p>{{lastName + " " + firstName}}</p>
<p>{{fullname}}</p>
<p>总价:{{totalPrice}}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script type="text/javascript">
const app = new Vue({
el:"#app",
data:{
message: "helloworld",
firstName:'照东',
lastName:'胡',
books:[
{id:1,name:'Java从入门到放弃',price:50},
{id:1,name:'C语言从入门到放弃',price:80},
{id:1,name:'Swift从入门到放弃',price:10},
{id:1,name:'Photoshop从入门到放弃',price:120}
]
},computed:{
fullname:function(){
return this.lastName + ' ' +this.firstName;
},
totalPrice:function(){
let total = 0;
this.books.forEach((book)=>{
total += book.price;
})
return total;
}
}
});
</script>
</body>
3.1 计算属性的get set方法
<div id="app">
<p>{{fullName}}</p>
<p>{{lastName + ' ' + firstName}}</p>
<p v-text="fullName"></p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script type="text/javascript">
const app = new Vue({
el:"#app",
data:{
firstName:'照东',
lastName:'胡'
},computed:{
fullName:{
set: function(newValue){
console.log("---" + newValue);
const names = newValue.split(' ');
this.lastName = names[0];
this.firstName = names[1];
},
get: function(){
console.log("--get--");
return this.lastName + ' ' + this.firstName;
}
}
}
});
</script>
控制台console执行语句:app.fullName = ‘张 三’; 会调用set方法
3.2 计算属性和methods区别
计算属性有缓存机制,其会观察相关属性是否发送变化;只有发生变化才能执行计算逻辑。但是mothods方法是调用几次执行几次。
<div id="app">
<p>插值表达式:</p>
<p>{{lastName + " " + firstName}}</p>
<p>插值表达式:</p>
<p>{{getFullName()}}</p>
<p>{{getFullName()}}</p>
<p>{{getFullName()}}</p>
<p>{{getFullName()}}</p>
<p>计算属性</p>
<p>{{fullName}}</p>
<p>{{fullName}}</p>
<p>{{fullName}}</p>
<p>{{fullName}}</p>
<p>{{fullName}}</p>
<p>{{fullName}}</p>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script type="text/javascript">
const app = new Vue({
el:"#app",
data:{
firstName:'照东',
lastName:'胡'
},methods:{
getFullName:function(){
console.log("--methods--");
return this.lastName + " " + this.firstName;
}
},computed:{
fullName:{
set: function(newValue){
console.log("---" + newValue);
const names = newValue.split(' ');
this.lastName = names[0];
this.firstName = names[1];
},
get: function(){
console.log("--get--");
return this.lastName + ' ' + this.firstName;
}
}
}
});
</script>
效果:
本文由 huzd 创作,采用 知识共享署名4.0 国际许可协议进行许可本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名最后编辑时间
为:
2021/12/20 19:43