最近换公司了,不再写c++了,用go写代码简直太感动了,啥也不用想,“想当然”的做就可以实现的又快又好。以实习生身份入职一个月就写完了一个面向全公司的公共服务的一期后台开发。前台一期交给了同事开发,二期我需要接过来,所以有机会接触一下前台了。
我们使用的是Vue框架。学了几天了。学习资料使用了清华大学出版社出的Vue.js实战。其中有一个示例代码:简单购物车。简单易理解,适合初学。现贴上源代码。
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>购物车示例</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" media="screen" href="style.css" />
</head>
<body>
<!-- v-cloak:隐藏标签直至示例准备完毕 -->
<div id="app" v-cloak>
<template v-if="list.length">
<table>
<!-- 标题 -->
<thead>
<tr>
<th></th>
<th>商品名称</th>
<th>商品单价</th>
<th>购买数量</th>
<th>操作</th>
</tr>
</thead>
<!-- 表格内容 -->
<tbody>
<tr v-for="(item, index) in list">
<td>{{index+1}}</td>
<td>{{item.name}}</td>
<td>{{item.price}}</td>
<td>
<!-- 减到1不能再减 -->
<button @click="handleReduce(index)":disabled="item.count===1">-</button>
{{item.count}}
<button @click="handleAdd(index)">+</button>
</td>
<td>
<button @click="handleRemove(index)">移除</button>
</td>
</tr>
</tbody>
</table>
<div>总价: ¥{{ totalPrice }}</div>
</template>
<div v-else>购物车为空</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.7/dist/vue.js"></script>
<script src="index.js"></script>
</body>
</html>
index.js
var app = new Vue({
el:'#app',
data: {
list: [
{
id:1,
name:'iPhone 7',
price:6188,
count:1
},
{
id:2,
name:'iPhone 8',
price:7988,
count:1
},
{
id:3,
name:'iPad Pro',
price:5888,
count: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;
}
// g:全局替换 B:非边界; +:一次或多次 $结尾
return total.toString().replace(/\B(?=(\d{3})+$)/g,', ')
}
},
methods: {
handleReduce: function(index){
if (this.list[index].count === 1)return;
this.list[index].count--;
},
handleAdd(index){
this.list[index].count++;
},
handleRemove:function(index){
this.list.splice(index, 1);
}
}
});