基于Vuejs实现购物车功能
本文实例为大家分享了Vuejs购物车实现代码,供大家参考,具体内容如下
html:
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<title>我的vue购物车</title>
<linkrel="stylesheet"href="css/bootstrap.min.css">
<linkrel="stylesheet"href="css/style.css">
<scriptsrc="js/vue.js"></script>
<scriptsrc="js/data.js"></script>
</head>
<body>
<divclass="container">
<templatev-if="data.length">
<h3>我的购物车:</h3>
<divclass="product">
<divclass="item">
<spanclass="btnbtn-default">商品名称</span>
<spanclass="btnbtn-defaultleft">商品单价</span>
<spanclass="btnbtn-defaultleft">商品数量</span>
<spanclass="btnbtn-defaultleft">操作</span>
</div>
<divclass="item"style="padding:5%;border:1pxsolidblack"v-for="itemindata">
<spanclass="btnbtn-default">{{item.name}}</span>
<spanclass="btnbtn-defaultleft"style="margin-left:18%">{{item.price}}</span>
<span>
<emclass="btnbtn-primaryadd"v-on:click="add($index)":class="{off:item.count==11}">+</em>
{{item.count}}
<emclass="btnbtn-primaryreduce"v-on:click="reduce($index)":class="{off:item.count==1}">-</em>
</span>
<spanclass="btnbtn-dangerleft"v-on:click="remove(item)">移除</span>
</div>
</div>
<h2>清单:</h2>
<spanclass="btnbtn-primary">商品总价:{{price|currency'$'2}}</span>
</template>
<templatev-else>
<divclass="jumbotron">
<h1>您的购物车空了</h1>
<p>是否去重新挑选</p>
<p><aclass="btnbtn-primarybtn-lg"href="#"role="button">重新挑选</a></p>
</div>
</template>
</div>
</body>
<script>
newVue({
el:'.container',
data:{
data:data
},
computed:{
price:function(){
varprice=0;
for(vari=0;i<this.data.length;i++){
varself=this.data[i];
price+=self.count*self.price;
}
returnprice;
}
},
methods:{
add:function($index){
varself=this.data[$index];
if(self.count>10){
returnfalse;
}
self.count++;
},
reduce:function($index){
varself=this.data[$index];
if(self.count<=1){
returnfalse
}
self.count--;
},
remove:function(item){
this.data.$remove(item);
}
}
})
</script>
</html>
css:
h3{
text-align:center;
}
.left{
margin-left:14%;
}
.item{
text-align:center;
padding:3%;
}
.add{
margin-left:15%;
}
.off{
background-color:lightgrey;
border:1pxsolidlightgrey;
}
js:
/**
*CreatedbyAdministratoron2016/7/29.
*/
vardata=[
{
name:'IPhone6',
price:5466,
id:1,
count:1
},
{
name:'IMac',
price:7466,
id:2,
count:1
},
{
name:'iPad',
price:5400,
id:3,
count:1
}
]
本文已被整理到了《Vue.js前端组件学习教程》,欢迎大家学习阅读。
关于vue.js组件的教程,请大家点击专题vue.js组件学习教程进行学习。
更多vue学习教程请阅读专题《vue实战教程》
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。