计算属性computed,可以将属性进行拼接,计算生成新的属性,计算属性的结果会被缓存,效率较高。
属性拼接
通过computed可以将多个属性拼接到一起,返回一个新的属性,避免用{{mustache}}语法拼接。用computed可以将结果缓存,比methods效率高。如下所示,将data中的三个属性拼接到一起返回。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="../js/vue.js"></script>
</head>
<body>
<div id="app">
<p>{{allwords}}</p>
</div>
<script>
const vue = new Vue({
el:"#app",
data:{
firstword:"hello",
secondword:"vue",
thirdword:"!"
},
computed:{
allwords:function(){
return this.firstword+" " +this.secondword+this.thirdword
}
}
});
</script>
</body>
</html>
属性计算
通过computed还可以计算生成一个新的属性,如下所示,通过计算属性,返回所有书的总价格。
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="../js/vue.js"></script>
</head>
<body>
<div id="app">
<p>总价格:{{totalprice}}</p>
</div>
<script>
const vue = new Vue({
el:"#app",
data:{
books:[{name:'哈利波特与死亡圣器',price:'50',count:'2'},
{name:'老人与海',price:'50',count:'3'},
{name:'三个火枪手',price:'50',count:'2'}]
},
computed:{
totalprice:function(){
let total=0;
for(let i=0;i<this.books.length;i++)
{
total+=this.books[i].price*this.books[i].count;
}
return total;
}
}
});
</script>
</body>
</html>
效果如下