開始學習Vue的小白,dalao多多指正
想要實現下面這個界面,包含總價計算、數量增加和移除功能

話不多說代碼如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title>小購物車</title>
</head>
<body>
<div id="app">
<table border="2">
<thead>
<td>書籍名稱</td>
<td>書籍名稱</td>
<td>出版日期</td>
<td>價格</td>
<td>購買數量</td>
<td>操作</td>
</thead>
<tbody>
<tr v-for="(item,index) in books" >
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.date}}</td>
<td>{{item.price | showPrice}}</td>
<td>
<button @click="decrement(index)" v-bind:disabled="item.count <= 1">-</button>
{{item.count}}
<button @click="increment(index)">+</button>
</td>
<td>
<button @click="removeBook(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<font>總價:{{toltalPrice | showPrice}}</font>
</div>
<script src="./js/vue.js"></script>
<script>
const hello = new Vue({
el:'#app',
data:{
message:'Hello Vue !',
books :[
{
id:1,
name:'編程大法',
date:'2020-5',
price:999.00,
count:1
},
{
id:2,
name:'編程大法',
date:'2020-5',
price:999.00,
count:1
},
{
id:3,
name:'編程大法',
date:'2020-5',
price:999.00,
count:1
},
{
id:4,
name:'編程大法',
date:'2020-5',
price:999.00,
count:1
}
]
},
filters: {
showPrice(price) {
return '¥'+price.toFixed(2);
}
},
methods:{
decrement(index){
this.books[index].count--;
},
increment(index){
this.books[index].count++;
},
removeBook(index){
this.books.splice(index,1);
}
},
computed:{
toltalPrice(){
let toltalPrice=0;
for(let i=0;i<this.books.length;i++){
toltalPrice += this.books[i].price * this.books[i].count;
}
return toltalPrice;
}
}
})
</script>
</body>
</html>
v-for:以前用原生javascript寫界面的時候想要呈現出一個列表的效果需要在html中寫多個<tr></tr>、<td></td>、<th></th>標簽,使代碼過於冗余,這就是框架好處之一啊哈哈。
<tr v-for="(item,index) in books" >
這個寫法使item(books數組的項逐一遍歷),index會記錄數組下標
computed和methods
這也是比較巧妙的地方之一:雖然兩者的內容都可以寫函數,但是不同之處在於computed里的函數在頁面加載時執行一次並且將內容保存在內存中,在下一次使用函數時不用重新調用,直接從內存中拿出來用就行會比methods里的函數節約內存,提高性能,對於頻繁使用的函數可以寫在computed里面,另外寫在標簽中時,computed里的函數只需要寫函數名,methods里的需要寫括號。但是computed會占用內存,所以不頻繁調用的可以寫在methods里面。computed類似於Vue中的屬性,在計算結果發生改變時,結果會動態地發生改變
