Shopping cart generally contains product name, unit price, quantity and other information, the quantity can be added or reduced at will, the item can also be deleted, and can also support full or multiple selection:
We split this small project into three files:
- Index.html (page)
- Index.js (Vue script)
- Style.css (Style)
1 index.js
First, initialize the Vue instance in JS. The overall template is as follows:
var app = new Vue({
el: '#app',
data: {
...
},
mounted: function() {... }, computed: { ... }, methods: { ... }});Copy the code
Generally speaking, the data here comes from the server data, so for simplicity, the data is directly defined:
Data: {/** * list of items in the shopping cart */ list: [{id: 1, name:'Seaweed imported from Korea', price: 39.9, count: 1}, {id: 2, name:'Nabati Richoco Chocolate Flavored Wafers imported from Indonesia', price: 11.8, count: 1}, {id: 3, name:'Philippines import Dodgegrass Creamer', price: 6.5, count: 1}], // List of selected items used to calculate total price checkList: []}Copy the code
- List displays a list of items in a shopping cart.
- CheckList is used to represent the list of selected items. Later, we will use it to calculate the total price of selected items.
mounted: function() {this.checkall (); this.checkAllElement(document.querySelector(".checkAll"));
}
Copy the code
If Mounted, all items in the shopping cart are selected by default.
Computed: {/** * totalPrice * @returns {string} */ totalPrice:function () {
var total = 0;
for (var i = 0; i < this.checkList.length; i++) {
var item = this.checkList[i];
total += item.price * item.count;
}
returntotal.toLocaleString(); }}Copy the code
In the calculation attribute, we define the calculation method of the total price, which is bound to a checkList to calculate the total price. The toLocaleString method is used because decimals are automatically rounded and conveniently expressed in thousandths
Methods: {/** * reduce the number of purchases * @param index */ reduceCount:function (index) {
if (this.list[index].count === 1) return; this.list[index].count--; }, /** * increase the number of purchases * @param index */ addCount:function(index) { this.list[index].count++; }, /** * remove item * @param index */ remove:function (index) {
console.log("remove-index:"+ index); this.list.splice(index, 1); Var id = index + 1; // Remove the item var that actually participates in the calculation$checkList = this.checkList;
for (var i = 0; i < $checkList.length; i++) {
var item = $checkList[i];
if (item.id == id) {
$checkList.splice(i, 1); }}}, /** * all or none * @param event */ checkAllOrNot:function (event) {
if(event.target.checked) {// select this.checkAll(); console.log("checkList:" + this.checkList);
} else{// No console.log("None at all");
this.checkInItems('noCheckAll'); this.checkList.splice(0); }}, /** * all */ checkAll:function () {
console.log("Future generations");
this.checkInItems('checkAll'); this.checkList = this.list.concat(); /** * select all or none * @paramtypeCheckAll: select all. Others: none */ checkInItems:function (type) {
var items = document.querySelectorAll('.checkItem');
for (var i = 0; i < items.length; i++) {
var item = items[i];
if (type= = ='checkAll') {
item.checked = true;
} else {
item.checked = false; }}}, /** * checked or unchecked */ checkItem:function (event, index) {
console.log("checkItem");
var element = event.target;
var $allCheck = document.querySelector(".checkAll");
if(element.checked) {// Check to add the selected list this.checklist.push (this.list[index]); this.checkAllElement($allCheck);
} else{// Uncheck to remove this.checklist. splice(index, 1) from the selected list;$allCheck.checked = false; }}, /** * check the box * @param element */ checkAllElement:function(Element) {// If all items are checked, check the full boxif (this.checkList.length == this.list.length) {
element.checked = true; }}}Copy the code
In Methods, we define the following functional methods:
- Reduce and increase the number of purchases. In the reduced-purchase method, we double-check the number of items currently in use to make the code more robust (the HTML template can be modified, the button replaced with a div or span, and the disabled style becomes invalid).
- Remove an item. Because the number of items in the shopping cart may differ from the number of items actually checked, we must delete them by finding the item ID.
- Check related operations (all, none, single, single none, etc.)
2 style.css
[v-cloak] {
display: none;
}
table {
border: 1px solid #e9e9e9;
border-collapse: collapse;
border-spacing: 0;
empty-cells: show;
}
th {
font: bold 12px "Trebuchet MS", Verdana, Arial, Helvetica, sans-serif;
color: #4f6b72;
border-right: 1px solid #C1DAD7;
border-bottom: 1px solid #C1DAD7;
border-top: 1px solid #C1DAD7;
letter-spacing: 2px;
text-transform: uppercase;
text-align: left;
padding: 6px 6px 6px 12px;
background: #CAE8EA;
}
td {
border-right: 1px solid #C1DAD7;
border-bottom: 1px solid #C1DAD7;
background: #fff;
font-size:14px;
padding: 6px 6px 6px 12px;
color: #4f6b72;
}
Copy the code
The V-cloak style is defined to solve the problem of the blink screen when the network is slow. The related styles of the table are also defined.
3 index.html
The Vue script and style file are then introduced in index.html. The basic template is as follows:
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8"> <title> Shopping cart </title> <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div id="app" v-cloak>
...
</div>
<script src="https://cdn.bootcss.com/vue/2.2.2/vue.min.js"></script>
<script src="index.js"></script>
</body>
</html>
Copy the code
Since it is possible that all items in the cart will be deleted, we have added a judgment here. If the list is empty, a friendly warning will be given:
<template v-if="list.length">... </template> <! <div v-else> There are no items in the shopping cart </div>Copy the code
Then use the table to show the list of goods in the shopping cart:
<table>
<thead>
<tr>
<th><input id="checkAll" type="checkbox" class="checkAll" @click="checkAllOrNot($event)"> < / th > < th > number < / th > < th > products < / th > < th > unit price < / th > < th > < / th > < th > action < / th > < / tr > < thead > < tbody > < tr v - for ="(item,index) in list">
<td><input type="checkbox" class="checkItem" @click="checkItem($event,index)"></td>
<td>{{index+1}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<button @click="reduceCount(index)" :disabled="item.count===1">-</button>
{{item.count}}
<button @click="addCount(index)">+</button>
</td>
<td>
<button @click="remove(index)"> delete < / button > < / td > < / tr > < / tbody > < / table > < div > total price: ${{totalPrice}} < / div >Copy the code
- Using the V-for command, loop through the list of items.
- Each check box and button in the table is bound to an event. The full box and the check box for each line are also passed native DOM events
$event
Gets the element that is currently being manipulated. * The button to reduce the number of items is determined here, and when only one item is left, bind the disabled style to make it unavailable.
4 the demonstration
This article is an example DEMO.