Vue实现购物车的简单页面
第一部分:
引入vue.js:
<script type="text/javascript" src="js/vue.js" ></script>
<script type="text/javascript" src="js/vue.min.js" ></script>
第二部分:
html代码:div布局,表格嵌套
<div id = "app">
<div v-if="shops.length >0">
<table border="1" cellspacing ='6' cellpadding="2">
<tr>
<th v-for="mo in title">{{mo}}</th>
</tr>
<tr v-for="(s,i) in shops" >
<!--<td>{{i+1}}</td>-->
<!--<td v-for="so in s">{{so}}</td>-->
<td><img src="img/鼠标1.png" /></td>
<td>{{s.id}}</td>
<td>{{s.name}}</td>
<td>{{s.data}}</td>
<td>
¥:{{s.price}}
</td>
<td>
<button v-on:click="btnadd(i)"> 加</button>
{{s.count}}
<button v-on:click="btndelete(i)"> 减</button>
</td>
<td><button v-on:click="btnremove(i)">移除</button></td>
</tr>
<tr>
<td colspan="7">总价格: {{allprice}}</td>
</tr>
</table>
</div>
<div v-else="">
<h1>购物车为空</h1>
</div>
</div>
第三部分:
js代码:主要使用vue中的el,data,methods,computed四个常用属性
<script>
const app = new Vue({
el:"#app",
data:{
title:['商品图片','序号','商品名','时间','价格','数量'],
shops:[
{id:1,name:'Vue.js实战',data:'2015-11-19',price:35,count:1},
{id:2,name:'Vue.js实战',data:'2014-03-21',price:45,count:1},
{id:3,name:'Vue.js实战',data:'2012-05-03',price:85,count:1},
{id:4,name:'Vue.js实战',data:'2016-01-01',price:73,count:1},
{id:5,name:'Vue.js实战',data:'2017-08-15',price:15,count:1},
]
},
methods:{
btnremove:function(i){
this.shops.splice(i,1);
},
btnadd:function(i){
this.shops[i].count++;
},
btndelete:function(i){
if(this.shops[i].count <=1){
alert("");
}else{
this.shops[i].count--;
}
}
},
computed:{
allprice:function(){
let result = 0;
let chen = 0;
for(let i = 0;i<this.shops.length;i++){
result+= this.shops[i].price*this.shops[i].count;
}
return result;
}
}
});
</script>
第四部分:
css代码:图片在鼠标悬停时放大图片的效果
img{
width: 50px;
height: 50px;
}
img:hover{
width: 100px;
height: 100px;
}