vueシンプルなカートを実現
11290 ワード
最近vue小demoを書く時、いくつかの小さな穴に出会って、まとめてみんなと分かち合って、まずコードを書きます:
html:
app.js:
ピットポイント:
html:
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title> title>
<link rel="stylesheet" href="style.css" type="text/css"/>
head>
<body>
<div id="app" on-cloak>
<div v-if="list.length>0">
<table>
<thead>
<tr>
<th>th>
<th> th>
<th> th>
<th> th>
<th> th>
tr>
thead>
<tr v-for="(item,index) in list" >
<td>{{index+1}}td>
<td>{{item.name}}td>
<td>{{item.price}}td>
<td>
<button @click="reduce(index)" :disabled="item.count===1">-button>
{{item.count}}
<button @click="add(index)">+button>
td>
<td><button @click="remove(index)"> button>td>
tr>
table>
<div > :{{totalPrice}}div>
div>
<div v-else> div>
div>
body>
<script src="../vue.js">script>
<script src="app.js">script>
html>
app.js:
var app = new Vue({
el: "#app",
data: {
list: [{
id: 1,
name: 'iphone7',
price: 6188,
count: 1
}, {
id: 2,
name: 'ipad pro',
price: 5188,
count: 1
}, {
id: 3,
name: 'MacBook pro',
price: 188888,
count: 1
}]
},
methods: {
add: function(index) {
this.list[index].count++;
},
reduce: function(index) {
if (this.list[index].count === 1) return;
this.list[index].count--;
},
remove: function(index) {
//
this.list.splice(index, 1);
}
},
computed: {
totalPrice: function() {
var total = 0;
for (var i = 0; i < this.list.length; i++) {
var item = this.list[i];
total += item.price * item.count
}
return total.toString().replace(/\B(?=(\d{3})+$)/g, ',');
}
}
})
ピットポイント:
<tbody>tbody> v-for tbody ,
vue list :
Vue.set(app.list,3,{
id: 2,
name: 'ipad pro',
price: 5188,
count: 1
})
:
list.splice(index) ,list[index].splice(index)
:
app.list.splice(3,1,{
id: 2,
name: 'ipad pro',
price: 5188,
count: 1
})