VUE指令(二)
computed
■我们知道,在模板中可以直接通过插值语法显示一些data中的数据。
■但是在某些情况,我们可能需要对数据进行一些转化后再显示 ,或者需要将多个数据结合起来进行显示
比如我们有firstName和lastName两个变量,我们需要显示完整的名称。
但是如果多个地方都需要显示完整的名称,我们就需要写多个{{firstName}} {{lastName}}
■我们可以将上面的代码换成计算属性:computed
<div id="app">
<h2>{{fullname}}</h2>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
firstName: 'aaa',
lastName: 'bbb'
},
computed: {
fullname() {
return this.firstName + ' ' + this.lastName
}
},
})
</script>
getter和setter:
<body>
<div id="app">
<h2>{{fullname}}</h2>
</div>
</body>
<script src="../js/vue.js"></script>
<script>
const app = new Vue({
el: '#app',
data: {
message: 'as',
firstname: 'aa',
lastname: 'bbb'
},
computed: {
fullname: {
set(n) {
console.log(n)
const names = n.split(' ')
this.firstname = names[0]
this.lastname = names[1]
},
get() {
return this.firstname + ' ' + this.lastname
}
}
},
})
</script>
用computed写的一个小案例:
<body>
<div id="app">
<div v-if="books.length">
<table>
<thead>
<tr>
<th></th>
<th>书籍名称</th>
<th>出版日期</th>
<th>价格</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in books">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.data}}</td>
<!-- <td>¥{{item.price.toFixed(2)}}</td> -->
<!-- <td>{{getFinalPrice(item.price)}}</td> -->
<!-- 过滤器 -->
<td>{{item.price | showPrice}}</td>
<td>
<button @click="decrement(index)" :disabled="item.count <= 1">-</button>
{{item.count}}
<button @click="increment(index)">+</button>
</td>
<td><button @click="removehandle(index)">移除</button></td>
</tr>
</tbody>
</table>
<h3>总价格:{{totalprice | showPrice}}</h3>
</div>
<h2 v-else>购物车为空</h2>
</div>
</body>
<script>
const app = new Vue({
el: '#app',
data: {
books: [{
id: 1,
name: "《算法导论》",
data: '2006-9',
price: 85.00,
count: 1
},
{
id: 2,
name: "《编程》",
data: '2006-2',
price: 45.00,
count: 1
},
{
id: 3,
name: "《c语言》",
data: '2008-9',
price: 66.00,
count: 1
},
{
id: 4,
name: "《代码大全》",
data: '2003-9',
price: 44.00,
count: 1
},
]
},
methods: {
getFinalPrice(price) {
return '¥' + price.toFixed(2)
},
increment(index) {
this.books[index].count++
},
decrement(index) {
this.books[index].count--
},
removehandle(index) {
this.books.splice(index, 1)
}
},
//过滤器
filters: {
showPrice(price) {
return '¥' + price.toFixed(2)
}
},
computed: {
totalprice() {
let totalprice = 0
//方法一
// for (let i = 0; i < this.books.length; i++) {
// totalprice += this.books[i].price * this.books[i].count
// }
// return totalprice
//方法二
// for (let i in this.books) {
// totalprice += this.books[i].price * this.books[i].count
// }
// return totalprice
//方法三
// for(let item of this.books){
// totalprice = item.price*item.count
// }
// return totalprice
//方法四
return this.books.reduce(function (pre, book) {
return pre + book.price * book.count
}, 0)
}
},
})
</script>
效果图: