一、基本使用
<body>
<div id="app">
<!-- 使用函数定义进行字符串拼接-->
<h2>{{getFullName()}}</h2>
<!--使用计算属性进行字符串拼接,无需添加小括号-->
<h2>{{fullName}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
firstName: 'sun',
lastName: 'bo'
},
// 计算属性,起名字尽量不要动词,属性名词
computed: {
fullName:function(){
return this.firstName + " " + this.lastName
}
},
//
methods:{
getFullName(){
return this.firstName + " " + this.lastName
}
}
})
</script>
</body>
二、一些复杂操作
<body>
<div id="app">
<!-- 显示所有书的总价格-->
<h2>总价格:{{totalPrice}}</h2>
</div>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
books: [
{id: 110, name: 'Unix编程艺术', price:118},
{id: 111, name: '深入理解计算机原理', price:114},
{id: 112, name: 'Unix编程艺12', price:119},
{id: 113, name: 'Unix编45术', price:112},
]
},
// 计算属性
computed: {
// 使用计算属性对data数据进行汇总,然后在 html 模板中进行调用
totalPrice: function(){
let result = 0;
// ES5 语法循环
// for ( let i=0; i<this.books.length; i++){
// result += this.books[i].price
// }
// ES6 循环 1 获取的是下标
// for (i in this.books){
// result += this.books[i].price
// }
// ES6 循环2 可以直接获取数组里面的元素 !!
for (book of this.books){
result += book.price
}
return result
}
},
})
</script>
</body>