添加购物车数量功能实现
通过connect.js
import Vue from 'vue';
let connect = new Vue();
//向外导出
export default connect;
app.vue
<template>
<div>
<!-- 头部内容 -->
<mt-header title="传智27期信息管理系统"></mt-header>
<transition name="router" mode="out-in">
<router-view></router-view>
</transition>
<!-- 底部内容 -->
<nav class="mui-bar mui-bar-tab">
<router-link class="mui-tab-item" :to="{name:'home'}">
<span class="mui-icon icon-shouye1"></span>
<span class="mui-tab-label">首页</span>
</router-link>
<router-link class="mui-tab-item" :to="{name:'member'}">
<span class="mui-icon icon-diamond"></span>
<span class="mui-tab-label">会员</span>
</router-link>
<router-link class="mui-tab-item" :to="{name:'shopcart'}">
<span class="mui-icon icon-gouwucheman"><span class="mui-badge">{{pickNum}}</span></span>
<span class="mui-tab-label">购物车</span>
</router-link>
<router-link class="mui-tab-item" :to="{name:'search'}">
<span class="mui-icon mui-icon-search"></span>
<span class="mui-tab-label">查找</span>
</router-link>
</nav>
</div>
</template>
<script>
import connect from './components/common/connect.js';
//引入prodTools
import prodTools from './components/common/prodTools.js';
//先创建父组件,后创建子组件
export default {
data(){
return {
pickNum:prodTools.getTotalCount()
}
},
created(){//VueComponent Vue$3 代表new Vue()的对象
//this.pickNum; //这里的this是VueComponent
// 记录this:let self = this;
connect.$on('addShopcart',num => {
// this就是connect 而不是VueComponent
this.pickNum = this.pickNum + num;
//this.pick += num;
//
//
//
//
//
//记录this:self.pick += num;
})
}
}
</script>
<style scoped>
.router-enter-active,.router-leave-active{
transition: opacity .5s
}
.router-enter,.router-leave-to{
opacity: 0;
}
</style>
goodsdetail.vue 子组件
<template>
<div>
<nav-bar title="商品详情"></nav-bar>
<div class="outer-swiper">
<div class="swiper">
<my-swipe :url="goodsDetailUrl"></my-swipe>
</div>
</div>
<div class="product-desc">
<ul>
<li><span class="product-desc-span">
{{prodInfo.title}}
</span></li>
<li class="price-li">市场价:
<s>¥{{prodInfo.market_price}}</s> 销售价:<span>¥{{prodInfo.sell_price}}</span></li>
<li class="number-li">购买数量:<span @click="substract">-</span><span>{{num}}</span><span @click="add">+</span></li>
<li>
<mt-button type="primary">立即购买</mt-button>
<mt-button type="danger" @click="addShopcart">加入购物车</mt-button>
</li>
</ul>
</div>
<transition name="ball" @after-enter="afterEnter">
<div class="ball" v-if="isShow"></div>
</transition>
<div class="product-props">
<ul>
<li>商品参数</li>
<li>商品货号:{{prodInfo.goods_no}}</li>
<li>库存情况:{{prodInfo.stock_quantity}}件</li>
<li>上架时间:{{prodInfo.add_time | convertDate}}</li>
</ul>
</div>
<div class="product-info">
<ul>
<li>
<mt-button type="primary" size="large" plain @click="showPicInfo">图文介绍</mt-button>
</li>
<li>
<mt-button type="danger" size="large" plain @click="showProdComment">商品评论</mt-button>
</li>
</ul>
</div>
</div>
</template>
<script>
//vue中组件通信的对象
import connect from '../common/connect.js';
//引入prod工具对象
import prodTools from '../common/prodTools.js';
export default {
data(){
return {
isShow:false,//控制小球是否显示
imgs:[],//缩略图数组
prodInfo:{}, //商品信息
goodsDetailUrl:'',//商品详情轮播图url
num:1, //添加购物车的商品数量
}
},
created(){
//1:获取路由参数id
let id = this.$route.query.id;
//2:获取详情数据
// this.$ajax.get('goods/getinfo/' + id)
// .then(res=>{
// this.prodInfo = res.data.message[0];
// })
// .catch(err=>{
// console.log(err);
// })
// //3:获取轮播图数据
// this.$ajax.get('getthumimages/' + id)
// .then(res=>{
// this.imgs = res.data.message;
// })
// .catch(err=>{
// console.log(err);
// })
//拼接url:传递给子组件
this.goodsDetailUrl = 'getthumimages/' + id;
//使用合并请求
this.$ajax.all([
this.$ajax.get('goods/getinfo/' + id)
// ,this.$ajax.get('getthumimages/' + id)
])
//分发响应
.then(this.$ajax.spread( (resInfo)=>{
this.prodInfo = resInfo.data.message[0];
//this.imgs = resImgs.data.message;
}) )
.catch(err=>{
console.log(err);
})
},
methods:{
add(){
if(this.num >= this.prodInfo.stock_quantity) return;
this.num++;
},
substract(){
if(this.num <= 1) return;
this.num--;
},
//添加购物车
addShopcart(){
// console.log('开始emit');
connect.$emit('addShopcart',this.num);
//让小球飞起来,也就是插入ball这个元素
this.isShow = true;
//调用工具对象来添加商品
prodTools.addOrUpdate({
id:this.prodInfo.id,
num:this.num
})
//测试: 输出最终数据
// console.log(prodTools.getProds() );
},
//处理过渡效果进入之后的行为
afterEnter(){
this.isShow = false;//移除元素
},
showProdComment(){
//先获取当前商品id
let id = this.$route.query.id;
//编程导航
this.$router.push({
name:'goods.comment',
query:{ id } //路由参数id
});
},
showPicInfo(){
let id = this.$route.query.id;
//编程导航
this.$router.push({
name:'goods.pictureInfo',
query:{ id } //路由参数id
});
}
}
}
</script>
<style scoped>
.ball-enter-active{
animation: bounce-in .5s;
}
@keyframes bounce-in {
0% {
transform: translate3d(0, 0, 0);
}
50% {
/*x,y,z轴的位置*/
transform: translate3d(140px, -50px, 0);
}
75% {
transform: translate3d(160px, 0px, 0);
}
100% {
transform: translate3d(140px, 300px, 0);
}
}
.swiper {
border: 1px solid rgba(0, 0, 0, 0.2);
margin: 8px;
width: 95%;
border-radius: 15px;
overflow: hidden;
}
.outer-swiper,
.product-desc,
.product-props,
.product-info {
border-radius: 5px;
border: 1px solid rgba(0, 0, 0, 0.2);
margin: 3px;
}
/*请ulpadding*/
.outer-swiper ul,
.product-desc ul,
.product-props ul,
.product-info ul {
padding: 0;
}
.product-desc ul li,
.product-props ul li,
.product-info ul li {
list-style: none;
font-size: 15px;
color: rgba(0, 0, 0, 0.5);
margin-top: 8px;
}
.product-desc ul >:nth-child(1) span {
color: blue;
font-size: 22px;
font-weight: bold;
}
.product-desc ul >:nth-child(1) {
border-bottom: 1px solid rgba(0, 0, 0, 0.5);
}
.product-desc ul,
.product-info ul,
.product-props ul {
padding-left: 10px;
}
.price-li span {
color: red;
font-size: 25px;
}
.price-li s {
margin-right: 16px;
}
/*加减*/
.number-li span {
display: inline-block;
border: 2px solid rgba(0, 0, 0, 0.1);
width: 25px;
}
/*商品参数*/
.product-props ul >:nth-child(1) {
text-align: left;
}
.product-props ul:not(:nth-child(1)) {
margin-left: 40px;
}
.product-info ul {
margin-bottom: 70px;
padding: 0 5;
}
.number-li span {
text-align: center;
}
.number-li >:nth-child(2) {
width: 40px;
}
.ball {
border-radius: 50%;
background-color: red;
width: 24px;
height: 24px;
position: absolute;
top: 440px;
left: 120px;
display: inline-block;
z-index: 9999;
}
</style>
小球飞入功能
飞出并消失有js钩子实现 afterenter实现
<template>
<transition name="ball" @after-enter="afterEnter">
<div class="ball" v-if="isShow"></div>
</transition>
<js>
addShopcart(){
// console.log('开始emit');
connect.$emit('addShopcart',this.num);
//让小球飞起来,也就是插入ball这个元素
this.isShow = true;
//调用工具对象来添加商品
prodTools.addOrUpdate({
id:this.prodInfo.id,
num:this.num
})
//测试: 输出最终数据
// console.log(prodTools.getProds() );
},
//处理过渡效果进入之后的行为
afterEnter(){
this.isShow = false;//移除元素
},
<css>
<style scoped>
.ball-enter-active{
animation: bounce-in .5s;
}
@keyframes bounce-in {
0% {
transform: translate3d(0, 0, 0);
}
50% {
/*x,y,z轴的位置*/
transform: translate3d(140px, -50px, 0);
}
75% {
transform: translate3d(160px, 0px, 0);
}
100% {
transform: translate3d(140px, 300px, 0);
}
}
商品数量和本地储存
prodTools.js
let prodTools = {};
let store = window.localStorage;
// let prods = {没有数据就应该是空对象}; //未来从localStorage中获取
let prods = JSON.parse(store.getItem('prods')||'{}');
//{ id:num }
//增加或追加
prodTools.addOrUpdate = function(p){
//判断是否存在
if(prods[p.id]){//追加
prods[p.id] += p.num;
}else{
prods[p.id] = p.num;
}
//保存
this.saveProds(prods);
}
//删除
prodTools.delete = function(id){
delete prods[id];
//保存
this.saveProds(prods);
}
//获取到storage
prodTools.getProds = function(){
return JSON.parse(store.getItem('prods')||'{}');
}
//获取总数
prodTools.getTotalCount = function(){
let sum = 0;
for(let id in prods){
sum += prods[id];
}
return sum;
}
//存储
prodTools.saveProds = function(prods){
store.setItem('prods',JSON.stringify(prods));
}
export default prodTools;
goodsDetail.vue
<template>
<div>
<nav-bar title="商品详情"></nav-bar>
<div class="outer-swiper">
<div class="swiper">
<my-swipe :url="goodsDetailUrl"></my-swipe>
</div>
</div>
<div class="product-desc">
<ul>
<li><span class="product-desc-span">
{{prodInfo.title}}
</span></li>
<li class="price-li">市场价:
<s>¥{{prodInfo.market_price}}</s> 销售价:<span>¥{{prodInfo.sell_price}}</span></li>
<li class="number-li">购买数量:<span @click="substract">-</span><span>{{num}}</span><span @click="add">+</span></li>
<li>
<mt-button type="primary">立即购买</mt-button>
<mt-button type="danger" @click="addShopcart">加入购物车</mt-button>
</li>
</ul>
</div>
<transition name="ball" @after-enter="afterEnter">
<div class="ball" v-if="isShow"></div>
</transition>
<div class="product-props">
<ul>
<li>商品参数</li>
<li>商品货号:{{prodInfo.goods_no}}</li>
<li>库存情况:{{prodInfo.stock_quantity}}件</li>
<li>上架时间:{{prodInfo.add_time | convertDate}}</li>
</ul>
</div>
<div class="product-info">
<ul>
<li>
<mt-button type="primary" size="large" plain @click="showPicInfo">图文介绍</mt-button>
</li>
<li>
<mt-button type="danger" size="large" plain @click="showProdComment">商品评论</mt-button>
</li>
</ul>
</div>
</div>
</template>
<script>
//vue中组件通信的对象
import connect from '../common/connect.js';
//引入prod工具对象
import prodTools from '../common/prodTools.js';
export default {
data(){
return {
isShow:false,//控制小球是否显示
imgs:[],//缩略图数组
prodInfo:{}, //商品信息
goodsDetailUrl:'',//商品详情轮播图url
num:1, //添加购物车的商品数量
}
},
created(){
//1:获取路由参数id
let id = this.$route.query.id;
//2:获取详情数据
// this.$ajax.get('goods/getinfo/' + id)
// .then(res=>{
// this.prodInfo = res.data.message[0];
// })
// .catch(err=>{
// console.log(err);
// })
// //3:获取轮播图数据
// this.$ajax.get('getthumimages/' + id)
// .then(res=>{
// this.imgs = res.data.message;
// })
// .catch(err=>{
// console.log(err);
// })
//拼接url:传递给子组件
this.goodsDetailUrl = 'getthumimages/' + id;
//使用合并请求
this.$ajax.all([
this.$ajax.get('goods/getinfo/' + id)
// ,this.$ajax.get('getthumimages/' + id)
])
//分发响应
.then(this.$ajax.spread( (resInfo)=>{
this.prodInfo = resInfo.data.message[0];
//this.imgs = resImgs.data.message;
}) )
.catch(err=>{
console.log(err);
})
},
methods:{
add(){
if(this.num >= this.prodInfo.stock_quantity) return;
this.num++;
},
substract(){
if(this.num <= 1) return;
this.num--;
},
//添加购物车
addShopcart(){
// console.log('开始emit');
connect.$emit('addShopcart',this.num);
//让小球飞起来,也就是插入ball这个元素
this.isShow = true;
//调用工具对象来添加商品
prodTools.addOrUpdate({
id:this.prodInfo.id,
num:this.num
})
//测试: 输出最终数据
// console.log(prodTools.getProds() );
},
//处理过渡效果进入之后的行为
afterEnter(){
this.isShow = false;//移除元素
},
showProdComment(){
//先获取当前商品id
let id = this.$route.query.id;
//编程导航
this.$router.push({
name:'goods.comment',
query:{ id } //路由参数id
});
},
showPicInfo(){
let id = this.$route.query.id;
//编程导航
this.$router.push({
name:'goods.pictureInfo',
query:{ id } //路由参数id
});
}
}
}
</script>
<style scoped>
.ball-enter-active{
animation: bounce-in .5s;
}
@keyframes bounce-in {
0% {
transform: translate3d(0, 0, 0);
}
50% {
/*x,y,z轴的位置*/
transform: translate3d(140px, -50px, 0);
}
75% {
transform: translate3d(160px, 0px, 0);
}
100% {
transform: translate3d(140px, 300px, 0);
}
}
.swiper {
border: 1px solid rgba(0, 0, 0, 0.2);
margin: 8px;
width: 95%;
border-radius: 15px;
overflow: hidden;
}
.outer-swiper,
.product-desc,
.product-props,
.product-info {
border-radius: 5px;
border: 1px solid rgba(0, 0, 0, 0.2);
margin: 3px;
}
/*请ulpadding*/
.outer-swiper ul,
.product-desc ul,
.product-props ul,
.product-info ul {
padding: 0;
}
.product-desc ul li,
.product-props ul li,
.product-info ul li {
list-style: none;
font-size: 15px;
color: rgba(0, 0, 0, 0.5);
margin-top: 8px;
}
.product-desc ul >:nth-child(1) span {
color: blue;
font-size: 22px;
font-weight: bold;
}
.product-desc ul >:nth-child(1) {
border-bottom: 1px solid rgba(0, 0, 0, 0.5);
}
.product-desc ul,
.product-info ul,
.product-props ul {
padding-left: 10px;
}
.price-li span {
color: red;
font-size: 25px;
}
.price-li s {
margin-right: 16px;
}
/*加减*/
.number-li span {
display: inline-block;
border: 2px solid rgba(0, 0, 0, 0.1);
width: 25px;
}
/*商品参数*/
.product-props ul >:nth-child(1) {
text-align: left;
}
.product-props ul:not(:nth-child(1)) {
margin-left: 40px;
}
.product-info ul {
margin-bottom: 70px;
padding: 0 5;
}
.number-li span {
text-align: center;
}
.number-li >:nth-child(2) {
width: 40px;
}
.ball {
border-radius: 50%;
background-color: red;
width: 24px;
height: 24px;
position: absolute;
top: 440px;
left: 120px;
display: inline-block;
z-index: 9999;
}
</style>
计算购物车数量和购物车删除
<template>
<div class="tmpl">
<nav-bar title="购物车"></nav-bar>
<div class="pay-detail">
<ul>
<li v-for="(goods,index) in goodsList" :key="goods.id" class="p-list">
<mt-switch v-model="goods.isPicked"></mt-switch>
<img :src="goods.thumb_path">
<div class="pay-calc">
<p v-text="goods.title"></p>
<div class="calc">
<span>¥{{goods.sell_price}}</span>
<span @click="sub(index)">-</span>
<span >{{goods.num}}</span>
<span @click="add(index)">+</span>
<a href="javascript:;" @click="del(index)">删除</a>
</div>
</div>
</li>
</ul>
</div>
<div class="show-price">
<div class="show-1">
<p>总计(不含运费):</p>
<span>已经选择商品{{payment.num}}件,总价¥{{payment.sum}}元</span>
</div>
<div class="show-2">
<mt-button type="danger" size="large">去结算</mt-button>
</div>
</div>
</div>
</template>
<script>
//引入商品操作工具对象
import prodTools from '../common/prodTools.js';
//通知底部变更数据
import connect from '../common/connect.js';
export default {
data(){
return {
//也会将对象的子属性继续做defineProperty
//作为一个对象的属性,被Object.defineProperty(obj,'goodsList',{
// set:function(){ 当obj.goodsList=xxx的时候触发 }
//
//})
goodsList:[],//商品数组数据
}
},
created(){
//获取local的数据
let prods = prodTools.getProds();
//判断如果没有商品,return
if(Object.keys(prods).length === 0)return;
//prods{"87":4,"89":10,"93":11,"95":16}
let url = 'goods/getshopcarlist/';
url += Object.keys(prods).join(',');
//发起请求,将数据挂上
this.$ajax.get(url)
.then(res=>{
this.goodsList = res.data.message;
//prods{"87":4,"89":10,"93":11,"95":16} ele.id-> 87
this.goodsList.forEach((ele,index)=>{
if(prods[ele.id]){ //数量
//在vue中添加属性,是没有办法做到响应,setter
// ele.num = prods[ele.id];
// ele.isPicked = true;
//添加属性一定要this.$set
this.$set(ele,'num',prods[ele.id]);
this.$set(ele,'isPicked',true);
}
})
})
.catch(err=>{
console.log(err);
})
},
methods:{
add(i){
this.goodsList[i].num++;
connect.$emit('addShopcart',1);
prodTools.addOrUpdate({
id:this.goodsList[i].id,
num:1, //如果存在,追加1,否则新增1
})
},
sub(i){
if(this.goodsList[i].num<= 1) return;
this.goodsList[i].num--;
connect.$emit('addShopcart',-1);//加上-1就是减一
prodTools.addOrUpdate({
id:this.goodsList[i].id,
num:-1, //如果存在,追加1,否则新增1
})
},
del(i){
//删除内存,删除storage,通知下方number小球
let goods = this.goodsList[i];
//删除storage
prodTools.delete(goods.id)
//通知下方number小球
connect.$emit('addShopcart',-goods.num);
//删除内存
this.goodsList.splice(i,1);
}
},
computed:{
payment(){
// 1:如果商品没有被选中,遍历数组中,哪些商品有被选中,如果是
// 2:计算总金额= 单价 * 件数
// 3:将以上总金额累计
// 4:如果是 +元素的num 件数
let num = 0;
let sum = 0;
this.goodsList.forEach((ele)=>{
if(ele.isPicked){
//选中
sum += ele.num * ele.sell_price;//总价
num += ele.num;//金额
}
})
return {
num,sum
};
}
}
}
</script>
<style scoped>
.pay-detail ul li {
list-style: none;
border-bottom: 1px solid rgba(0, 0, 0, 0.2);
margin-bottom: 3px;
}
.pay-detail ul {
padding-left: 5px;
margin-top: 5px;
}
.pay-detail ul li img {
width: 80px;
height: 80px;
display: inline-block;
vertical-align: top;
margin-top: 10px;
}
.pay-detail ul li >:nth-child(1),
.pay-detail ul li >:nth-child(3) {
display: inline-block;
}
.pay-calc p {
display: inline-block;
width: 250px;
overflow: hidden;
color: blue;
font-size: 15px;
margin-bottom: 10px;
}
.pay-detail ul li >:nth-child(1) {
line-height: 80px;
}
.calc:nth-child(1) {
color: red;
font-size: 20px;
}
.calc span:not(:nth-child(1)) {
border: 1px solid rgba(0, 0, 0, 0.3);
display: inline-block;
width: 20px;
text-align: center;
}
.calc a {
margin-left: 20px;
}
.show-1,
.show-2 {
display: inline-block;
}
.show-1,
.show-2 {
margin-left: 30px;
}
.show-price {
background-color: rgba(0, 0, 0, 0.2);
}
</style>
淡入淡出效果
<transition name="router" mode="out-in">
<router-view></router-view>
</transition>
<style scoped>
.router-enter-active,.router-leave-active{
transition: opacity .5s
}
.router-enter,.router-leave-to{
opacity: 0;
}
</style>
打包
终端输入npm run build
当文件有改动,在webpack.config.js中改,第一种方法
output: {
//所有产出资源路径
path: path.join(__dirname, 'dist_production'),
filename: 'build.js?v=1.1.1'
}
但是消耗很多流量
因此,为了使更新更细化,把js和css分离,使用提取css 插件
webpack.config.js
'use strict';
const path = require('path');
const htmlWebpackPlugin = require('html-webpack-plugin');
const version = 'v1.1.1';
const ExtractTextPlugin = require("extract-text-webpack-plugin");
//提取公共模块,其的依赖
const webpack = require('webpack');
//压缩混淆
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
module.exports = {
//入口
entry: {
main: './src/main.js',
//再加一个入口
vendors:['vue','vue-router','moment','axios','vue-preview'],
},
output: {
//所有产出资源路径
path: path.join(__dirname, 'dist_production'),
//设置资源路径的请求地址
// style.css -> /css/ assets/mui.ttf
// load的时候配置的name属性 assets/mui.ttf
publicPath:'/', // 企业中也可以是www.baidu.com/
// filename: 'build.js?v=1.1.1' dasdsasa2s3e43
filename: 'js/[name].[chunkhash:6].js',
},
module: {
loaders: [{
test: /\.css$/,
// loader: 'style-loader!css-loader!autoprefixer-loader'
// 打包提取css
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader!autoprefixer-loader"
})
},
{
test: /\.less$/,
loader: 'style-loader!css-loader!autoprefixer-loader!less-loader'
},
{
test: /\.(jpg|png|svg|ttf|woff|woff2|gif)$/,
loader: 'url-loader',
options: {
limit: 4096, //4096字节以上生成文件,否则base6
name: 'assets/[name].[ext]'
}
},
{
test: /\.js$/,
loader: 'babel-loader',
exclude: /node_modules/,
// options: { 如果多次使用babel-loader就需要多次options
// presets: ['es2015'], //关键字
// plugins: ['transform-runtime'], //函数
// }
},
// 解析vue-preview的es6代码
{
test: /vue-preview.src.*?js$/,
loader: 'babel-loader',
// options: { 建议使用.babelrc文件,在当前根目录就可以了
// presets: ['es2015'], //关键字
// plugins: ['transform-runtime'], //函数
// }
},
{
test: /\.vue$/,
loader: 'vue-loader'
}
]
},
plugins: [
//压缩混淆代码
new UglifyJSPlugin(),
new webpack.optimize.CommonsChunkPlugin({
//manifest 清单,用来记录使用者和第三方包的依赖关系
names:['vendors','manifest']
}),
//提取css插件,设置名称
new ExtractTextPlugin("css/style.[contenthash:6].css"),
new htmlWebpackPlugin({
template: './src/index.html'
}),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
})
]
}
还有以下没学完: