Vue實(shí)現(xiàn)簡單購物車小案例
更新時間:2021年10月18日 10:57:03 作者:熱愛的前端小劉
這篇文章主要為大家詳細(xì)介紹了Vue實(shí)現(xiàn)簡單購物車小案例,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實(shí)例為大家分享了Vue實(shí)現(xiàn)簡單購物車的具體代碼,供大家參考,具體內(nèi)容如下
HTML首頁
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="/css/index.css" >
</head>
<body>
<div id="app">
<div v-if="books.length != 0">
<table>
<thead>
<tr>
<th></th>
<th>書籍名稱</th>
<th>出版如期</th>
<th>價格</th>
<th>購買數(shù)量</th>
<th>操作</th>
</tr>
</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)" :disabled="item.count <= 1">-</button>
{{item.count}}
<button @click="increment(index)">+</button>
</td>
<td><button @click="removeHandle(index)">移除</button></td>
</tr>
</tbody>
</table>
<h2>總價格為:{{totalPrice | showPrice}}</h2>
</div>
<h2 v-else>購物車為空</h2>
</div>
<script src="/js/vue.js"></script>
<script src="/js/index.js"></script>
</body>
</html>
css代碼
* {
margin: 0;
padding: 0;
}
table {
margin: 100px 0 0 100px;
border: 1px solid #e9e9e9;
border-collapse: collapse;
border-spacing: 0;
}
th,
td {
padding: 8px 16px;
border: 1px solid #e9e9e9;
text-align: left;
}
th {
background-color: #f7f7f7;
color: black;
font-weight: 6000 ;
}
h2 {
width: 500px;
margin-left: 100px;
}
button {
padding: 5px;
}
js代碼(Vue)
const app = new Vue({
el:"#app",
data:{
books:[
{
id:1,
name:'《算法導(dǎo)論》',
date:'2019-2',
price:85.00,
count:1
},
{
id:2,
name:'《計算機(jī)基礎(chǔ)》',
date:'2019-2',
price:95.00,
count:1
},
{
id:3,
name:'《c++高級語言》',
date:'2019-2',
price:89.00,
count:1
},
{
id:4,
name:'《編譯原理》',
date:'2019-2',
price:77.00,
count:1
},
]
},
methods:{
decrement(index){
this.books[index].count--
},
increment(index){
this.books[index].count++
},
removeHandle(index){
this.books.splice(index,1)
}
},
computed:{
totalPrice(){
let finalPrice = 0
for(let i = 0; i < this.books.length; i++){
finalPrice += this.books[i].price * this.books[i].count
}
return finalPrice
}
},
filters:{
showPrice(price){
return '¥' + price.toFixed(2)
}
}
})
運(yùn)行結(jié)果

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
去除Element-Plus下拉菜單邊框的實(shí)現(xiàn)步驟
Element-Plus 是 Element UI 的 Vue 3 版本,它提供了一套完整的組件庫,在使用 Element-Plus 進(jìn)行開發(fā)時,我們可能會遇到需要自定義組件樣式的情況,本文將介紹如何使用 CSS 來去除 Element-Plus 下拉框的邊框,需要的朋友可以參考下2024-03-03
Vue+Vant實(shí)現(xiàn)7天日歷展示并在切換日期時實(shí)時變換功能
本文介紹了如何利用Vue和Vant框架結(jié)合moment.js插件來實(shí)現(xiàn)一個7天日歷展示功能,在這個功能中,用戶可以在切換日期時看到界面的實(shí)時變化,此外,文章還提供了代碼實(shí)現(xiàn)和效果測試的詳細(xì)步驟,幫助開發(fā)者能夠順利完成類似的項(xiàng)目開發(fā)2024-10-10
Vue elementUI 自定義表單模板組件功能實(shí)現(xiàn)
在項(xiàng)目開發(fā)中,我們會遇到這種需求,在管理后臺添加自定義表單,在指定的頁面使用定義好的表單,這篇文章主要介紹了Vue elementUI 自定義表單模板組件,需要的朋友可以參考下2022-12-12

