计算属性computed
1、认识计算属性computed
computed:将多个数据结合起来显示。
测试代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>1vue计算属性computed</title>
</head>
<body>
<div id="info">
<h3>{
{mes1 + ',' + mes2}}</h3>
<h3>{
{vae}}</h3>
<h3>总价:{
{sumPrice}}</h3>
</div>
<script src="../../js/vue.js"></script>
<script>
const info = new Vue({
el : "#info",
data : {
mes1 : "音乐纯粹",
mes2 : "爱V绝对",
articles :[
{
kind: 'cloth',name: 'adidas',price: 500},
{
kind: 'shoes',name: 'nike',price: 2000},
{
kind: 'hat',name: 'fish',price: 500},
{
kind: 'jacket',name: 'bosdeng',price: 500},
]
},
computed: {
vae() {
return this.mes1 + ',' + this.mes2;
},
sumPrice() {
let sprice = 0;
for (let i in this.articles) {
sprice += this.articles[i].price;
}
return sprice;
},
},
methods : {
}
})
</script>
</body>
</html>
2、computed之setter、getter
- 每个computed都包含一个set方法(写)和get方法(读)。
- 若computed中只定义了set方法则为只写,只定义了get方法则为只读,若定义了set和get方法则为可读可写。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>2vue计算属性computed之set+get</title>
</head>
<body>
<div id="info">{
{vae}}</div>
<script src="../../js/vue.js"></script>
<script>
const info = new Vue({
el : "#info",
data : {
mes1 : "音乐纯粹",
mes2 : "爱V绝对",
},
computed:{
vae : {
// computed之set、get方法的基本写法
// set : function () {
// console.log("执行vae的setter");
// },
// get : function () {
// return this.mes1 + this.mes2;
// }
// 简写set、get方法
set(newVae){
console.log("执行vae的setter");
//更改vae的内容->更改mes1、mes2的内容
this.mes1 = newVae.split(',')[0];
this.mes2 = newVae.split(',')[1];
},
get(){
return this.mes1 + ',' + this.mes2;
}
}
},
methods : {
}
})
</script>
</body>
</html>
初始状态(执行一次get方法)
执行一次set方法,之后自动调用了一次get方法。
3、computed与methods的区别
- vue内部对计算属性做了缓存,会识别调用的数据是否变化,多次使用同一个computed时只调用一次。
- 多次使用同一个methods方法,使用几次就调用几次,无缓存效果。
改变其中一个参数
测试代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>2vue计算属性computed之set+get</title>
</head>
<body>
<div id="info">
<!-- methods-->
<h2>{
{getVae()}}</h2>
<h2>{
{getVae()}}</h2>
<h2>{
{getVae()}}</h2>
<h2>{
{getVae()}}</h2>
<!-- computed-->
<h2>{
{vae}}</h2>
<h2>{
{vae}}</h2>
<h2>{
{vae}}</h2>
<h2>{
{vae}}</h2>
</div>
<script src="../../js/vue.js"></script>
<script>
const info = new Vue({
el : "#info",
data : {
mes1 : "音乐纯粹",
mes2 : "爱V绝对",
},
computed:{
vae : {
// computed之set、get方法的基本写法
// set : function () {
// console.log("执行vae的setter");
// },
// get : function () {
// return this.mes1 + this.mes2;
// }
// 简写set、get方法
set(newVae){
console.log("执行vae的setter");
//更改vae的内容->更改mes1、mes2的内容
this.mes1 = newVae.split(',')[0];
this.mes2 = newVae.split(',')[1];
},
get(){
console.log("调用一次computed的get方法");
return this.mes1 + ',' + this.mes2;
}
}
},
methods : {
getVae : function () {
console.log("调用一次methods方法");
return this.mes1 + ',' + this.mes2;
}
}
})
</script>
</body>
</html>