vue实现的仿淘宝购物车功能详解

2020-06-14 05:58:40易采站长站整理

本文实例讲述了vue实现的仿淘宝购物车功能。分享给大家供大家参考,具体如下:

下面是一张众所周知的淘宝购物车页面,今天要讲解的案例就是用vue.js做一个类似的页面

首先简单介绍一下可能会用到的一些vue.js的用法:

v-bind,绑定属性;例如v-bind:class=”{‘class1’:flag}”,这是常用的绑定样式的方法,如果flag为true则class=class1;v-bind:src=”image”,image就是图像的路径;

v-if=”flag”v-show=”flag”,如果flag为true,则绑定的为“可见”,不同的是v-show是一开始就渲染在DOM中的,改变的则是它的display而已,而v-if为false则是从HTML代码中移除;

v-on:@,样式绑定v-on:click=”dosomething()”或者@click=”dosomething()”,点击触发dosomething函数;

v-for循环,v-for=”item in items”,items为数组,item为items数组的值而不是索引;

要注意的是当this作用域的改变:当this作用域改变是我们设置var self = this,在之后的使用中用self代替;

下面是HTML代码:


<html>
<head>
<title>购物车</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="shop.css" rel="external nofollow" >
</head>
<body>
<div id="app">
<div class="header"><span style="margin-left: 75px;">商品</span><span style="margin-left: 70px;">单价</span><span style="margin-left: 35px;">数量</span><span style="margin-left: 40px;">总价</span></div>
<div v-for="item in goods">
<div class="show" v-show="item.selected">
<span class="choice" v-bind:class="{'checked':item.checked}" @click="check(item)"></span>
<div style="float:left;margin-left: 20px;"><img v-bind:src="item.image" v-bind:alt="item.alt" class="image"/><span class="text">{{item.name}}</span></div>
<span style="float:left;margin-left: 20px;margin-top:20px;width:40px;">{{item.price}}元</span>
<div style="float:left;margin-left: 30px;margin-top: 20px;">
<span v-on:click="changeNum(item,-1)"><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >-</a></span>
<input v-model="item.number" class="output" disabled/>
<span v-on:click="changeNum(item,1)"><a href="javascript:void(0)" rel="external nofollow" rel="external nofollow" rel="external nofollow" rel="external nofollow" >+</a></span>