初学vue案例之简单购物车实现
最近刚开始接触vue.js框架,就自己写了些小案例来练练手,适合初学者,简单易懂,也不需要太多基础,只要稍微懂点json,然后看过了一些基本的vue 教程就行了。需要自己导入vue.js ,话不多说 just do it!!!
- html代码
<div id="app">
<table id="tbl">
<tr>
<td>
<label>商品名称</label></td>
<td>
<input type="text" name="productName" v-model="name"></td>
<td>
<label>数量</label></td>
<td>
<input type="text" name="quantity" v-model="quantity"></td>
<td>
<label>单价</label></td>
<td>
<input type="text" name="price" v-model="price"></td>
<td>
<label>类别</label>
<select name="level1" v-model="idx" @change="reflash">
<option v-for="(index,item) in typeList" value="{{index}}">
{{item.text}}
</option>
</select>
<select name="level2" v-model="type">
<option v-for="(index,item) in typeList_item" value="{{index}}">
{{item}}
</option>
</select>
</td>
<td>
<button id="add" @click="addProducts">添加</button>
</td>
</tr>
</table>
<table id="content" >
<tr>
<td>编号</td>
<td>商品名称</td>
<td>类别</td>
<td>数量</td>
<td>单价</td>
<td>总价</td>
<td>操作</td>
</tr>
<tr v-for="(index,product) in products" >
<td>{{product.id}}</td>
<td>{{product.name}}</td>
<td>{{product.type}}</td>
<td>{{product.quantity}}</td>
<td>{{product.price}}</td>
<td>{{product.sumPrice}}</td>
<td><button type="button" @click="del(index)">删除</button></td>
</tr>
</table>
</div>
- js代码
new Vue({
el:'#app',
data:{
products:[],
name:"",
quantity:0,
price:0,
type:0,
idx:0,
typeList:[
{item:["天上飞的","地上跑的"],text:"动物"},
{item:["夏季","冬季"],text:"水果"}
],
typeList_item:["天上飞的","地上跑的"]
},
methods:{
addProducts (){//添加商品
let product = {}
product.name = this.name;
product.quantity = this.quantity;
product.price = this.price;
product.type = this.typeList_item[this.type];
product.sumPrice = this.quantity*this.price;
product.id = this.products.length+1;
this.products.push(product);
},
del (idx){//删除
this.products.splice(idx,1);
},
reflash(){//刷新二级子菜单
this.typeList_item = this.typeList[this.idx].item;
console.log(this.idx)
}
}
})
-css 代码
*{
margin: 0;
padding: 0;
}
#tbl {
width: 1000px;
height: 50px;
margin: 0 auto;
}
#tbl input {
height: 25px;
}
#tbl select {
width: 100px;
height: 30px;
}
#content {
width: 1000px;
margin: 0 auto;
border: 1px solid #333;
border-collapse: collapse;
font-size: 14px;
font-weight: 100;
}
#content td {
height: 30px;
border: 1px solid #333;
text-align: center;
margin: 0;
padding: 0;
}
#content input[type=text] {
height: 25px;
width: 35px;
border: none;
outline: none;
}