https://www.escook.cn/docs-uni-shop/

1、uni-app 和项目搭建

1.1 项目介绍

1.2 文档介绍

项目接口文档

1.3 什么是 uni-app

就是基于 vue 的一个框架, 一套代码,可以打包成 多个端的方案

1.4 下载和安装 HB

uni-app 官方 推荐使用 HB 开发

  • 模板丰富
  • 完善的智能提示
  • 一键运行

安装步骤

  1. 访问官网 HB官网
  2. 点击首页的 DOWNLOAD 按钮
  3. 选择下载 正式版 => app开发板

1.5 安装 scss插件

进入 插件市场 安装 就行

1.6 对 HB 进行个性化的配置

修改快捷键方案 工具=> 预设快捷键方案切换 => vscode
修改编辑器的基本设置 工具 => 设置 => 打开 Settings.json 进行按需配置

1.7 新建 uni-app 项目

  1. 文件 => 新建 => 项目
  2. 填写 项目基本信息
  3. 勾选 uni-app
  4. 设置项目地址
  5. 模板 选择 uni-ui 项目
  6. 创建

1.8 了解 uni 目录结构

┌─components         uni-app组件目录
│ └─comp-a.vue       可复用的a组件
├─pages              业务页面文件存放的目录
│ ├─index
│ │ └─index.vue      index页面
│ └─list
│ | └─list.vue       list页面
├─static             存放应用引用静态资源(如图片、视频等)的目录,注意:静态资源只能存放于此
├─main.js            Vue初始化入口文件
├─App.vue            应用配置,用来配置小程序的全局样式、生命周期函数等
├─manifest.json      配置应用名称、appid、logo、版本等打包信息
└─pages.json         配置页面路径、页面窗口样式、tabBar、navigationBar 等页面类信息

1.9 把项目运行到 微信开发者工具

1、 填写自己的微信小程序的 AppID
打开 manifest.json 文件 => 微信小程序配置

2、配置 “微信开发者工具” 的安装路径

目的就是 为了 在HB 写完代码 然后 在 微信开发者工具上 查看效果

工具 => 设置 => 运行配置 => 小程序运行配置

3、在 微信开发者工具中, 通过 设置 => 安全设置 面板,开启 微信开发者工具 的 服务端口
4、在 HB 中,点击菜单栏中的 运行 =>运行到小程序模拟器 => 微信开发者工具 将当前 uni-app 项目编译之后,自动运行到微信开发者工具中,从而方便查看项目效果与调试

1.10 配置 checkSite

打开 manifest.json 找到 源码试图 在 setting 加入 “checkSiteMap”:false 即可

1.11 使用 git 本地管理 项目

1、在项目根目录新建 .gitignore 忽略文件,并配置如下

 # 忽略 node_modules 目录/node_modules/unpackage/dist# 由于我们忽略了 unpackage 目录仅有的  dist 目录,因此默认情况下,unpackage 目录 不会被 git 追踪
# 为了让git 能够正常追踪 unpackage 目录,按照管理,我们可以在 unpackage 目录下 创建一个叫做 .gitkeep 的文件进行占位

2、 git init
3、 git add .
4、 git commit -m “init project”

1.12 把项目托管到码云上

1.13 创建 tabbar 对应的四个页面

# 查看分至列表
git branch# 创建新分支,要在 master 的分支基础之上创建
git branch 新分支名称# 切换分支
git checkout 分支名称# 切换和创建分支
git checkout -b 分支名称# 合并分支,如果要合并到 master 分支上,要先切换代 master 上 在执行
# 将 login 合并道 master 上
git merge login

创建 并 切换到 tabbar 分支
git checkout -b tabbar

创建页面

  1. 在 pages 目录上 右击,选择 新建页面
  2. 在弹出的窗口中,输入 页面名称,勾选 使用 scss 的页面,勾选 在 pages.json 中注册,勾选 创建同名目录
  3. 点击 创建

创建 home cate cart my

1.14 配置 tabbar 效果

将 static 替换掉,用 资料里面的

配置 pages.json 节点,增加 tabbar 节点,在 第一层节点里面

{"tabBar": {"selectedColor": "#C00000","list": [{"pagePath": "pages/home/home","text": "首页","iconPath": "static/tab_icons/home.png","selectedIconPath": "static/tab_icons/home-active.png"},{"pagePath": "pages/cate/cate","text": "分类","iconPath": "static/tab_icons/cate.png","selectedIconPath": "static/tab_icons/cate-active.png"},{"pagePath": "pages/cart/cart","text": "购物车","iconPath": "static/tab_icons/cart.png","selectedIconPath": "static/tab_icons/cart-active.png"},{"pagePath": "pages/my/my","text": "我的","iconPath": "static/tab_icons/my.png","selectedIconPath": "static/tab_icons/my-active.png"}]}
}

保存后,为什么看不到, 原因: 把 pages 节点的 index 页面删除掉

1.15 配置导航条的样式效果

也是在 pages.json 文件中修改即可

1.16 分支合并提交

git add .
git commit -m "完成了tabbar"# 将 tabbar分支 推送到远程仓库中
git push -u origin tabbar# 将本地分支 合并到  master 上
git checkout master
git merge tabbar# 别忘了 还没推送呢
git push# 删除 本地的 tabbar分支
git branch -d tabbar

2、首页功能实现

2.1 创建 home 子分支

git checkout -b home

2.2 安装并配置网络请求的第三方包

建议在 uni-app 项目中使用 @escook/request-miniprogram 第
三方包发起网络数据请求
官网地址
npm install @escook/request-miniprogram

# main.js
// 导入网络请求的包
// 按需导入 $http 对象
import { $http } from '@escook/request-miniprogram'
// 在 uni-app 项目中,可以把 $http 挂载到 uni 顶级对象之上,方便全局调用
uni.$http = $http
// 请求开始之前做一些事情
$http.beforeRequest = function (options) {uni.showLoading({title: '数据加载中...',})
}
$http.afterRequest = function () {uni.hideLoading()
}

2.3 请求轮播图数据

  1. 在data 中 定义轮播图的数组
  2. 在 onload 声明周期里面 获取轮播图数据的方法
  3. 在 methods 中定义获取轮播图数据的方法
 export default {data() {return {// 1. 轮播图的数据列表,默认是空数组swiperList: [],};},onLoad() {// 调用方法,获取轮播图数据this.getSwiperList()},methods: {async getSwiperList() {const {data: res} = await uni.$http.get('/api/public/v1/home/swiperdata')if (res.meta.status !== 200) {return uni.showToast({title: '数据请求失败!',duration: 1500,icon: 'none'})}this.swiperList = res.message},}}

2.4 渲染轮播图的ui结构

<template><view><!-- 轮播图区域 --><swiper :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" :circular="true"><!-- 循环渲染轮播图的 item 项 --><swiper-item v-for="(item, i) in swiperList" :key="i"><view class="swiper-item"><!-- 动态绑定图片的 src 属性 --><image :src="item.image_src"></image></view></swiper-item></swiper></view>
</template>
 swiper {height: 330rpx;.swiper-item,image {width: 100%;height: 100%;}}

2.5 配置小程序分包

我们在项目中,把 tabBar 相关的 四个页面放到主包中,其他页面(例如:商品详情页、商品列表页)放到分包中。在uni-app 项目中,配置分包的步骤如下

1、在根目录,创建分包的根目录,命名为 subpkg
2、在 pages.json 中,和pages 平级创建 subPackages 节点,用来定义分包的相关结构

 "subPackages": [{"root": "subpkg","pages": [{"path": "goods_detail/goods_detail"}]}],

3、在 subpkg 目录上 右击 创建 goods_detail 页面

2.6 点击轮播图跳转到商品详情页面

1、讲 swiper-item 节点内的 view 组件 改造为 navigator 导航组件
2、动态绑定 id 值

<navigator class="swiper-item" :url="'/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id"><!-- 动态绑定图片的 src 属性 --><image :src="item.image_src"></image>
</navigator>

2.7 封装 uni.$showMsg()方法

在 main.js 中

//  封装 方法
// 封装的展示消息提示的方法
uni.$showMsg = function(title = '数据加载失败!', duration = 1500) {uni.showToast({title,duration,icon: 'none',})
}

2.8 获取 分类导航的数据

export default {data() {return {// 1. 分类导航的数据列表navList: [],}},onLoad() {// 2. 在 onLoad 中调用获取数据的方法this.getNavList()},methods: {// 3. 在 methods 中定义获取数据的方法async getNavList() {const { data: res } = await uni.$http.get('/api/public/v1/home/catitems')if (res.meta.status !== 200) return uni.$showMsg()this.navList = res.message},},
}

2.9 渲染分类导航的UI结构

     <!-- 分类导航区域 --><view class="nav-list"><view class="nav-item" v-for="(item, i) in navList" :key="i"><image :src="item.image_src" class="nav-img"></image></view></view>

2.10 点击第一项,跳转到分类页面

     <!-- 分类导航区域 --><view class="nav-list"><view class="nav-item" v-for="(item, i) in navList" :key="i" @click="navClickHandler(item)"><image :src="item.image_src" class="nav-img"></image></view></view>navClickHandler(item) {if (item.name === '分类') {uni.switchTab({url: '/pages/cate/cate'})}}

2.11 获取楼层的数据

export default {data() {return {// 1. 楼层的数据列表floorList: [],}},onLoad() {// 2. 在 onLoad 中调用获取楼层数据的方法this.getFloorList()},methods: {// 3. 定义获取楼层列表数据的方法async getFloorList() {const { data: res } = await uni.$http.get('/api/public/v1/home/floordata')if (res.meta.status !== 200) return uni.$showMsg()this.floorList = res.message},},
}

2.12 渲染楼层的标题

2.13 渲染楼层左侧的大图片

2.14 渲染楼层右侧小图片

<!-- 楼层区域 --><view class="floor-list"><!-- 楼层 item 项 --><view class="floor-item" v-for="(item, i) in floorList" :key="i"><!-- 楼层标题 --><image :src="item.floor_title.image_src" class="floor-title"></image><!-- 楼层图片区域 --><view class="floor-img-box"><!-- 左侧大图片的盒子 --><view class="left-img-box"><image :src="item.product_list[0].image_src":style="{width: item.product_list[0].image_width + 'rpx'}" mode="widthFix"></image></view><!-- 右侧 4 个小图片的盒子 --><view class="right-img-box"><view class="right-img-item" v-for="(item2, i2) in item.product_list" :key="i2" v-if="i2 !== 0"><image :src="item2.image_src" mode="widthFix" :style="{width: item2.image_width + 'rpx'}"></image></view></view></view></view></view>.floor-title {height: 60rpx;width: 100%;display: flex;}.right-img-box {display: flex;flex-wrap: wrap;justify-content: space-around;}.floor-img-box {display: flex;padding-left: 10rpx;}

2.15 点击楼层图片跳转到商品列表

1、在 subpkg 分包中,创建 goods_list 页面

2、 在获取 楼层列表数据 的函数中,在 设置data 的 floorList 之前

  // 通过双层 forEach 循环,处理 URL 地址res.message.forEach(floor => {floor.product_list.forEach(prod => {prod.url = '/subpkg/goods_list/goods_list?' + prod.navigator_url.split('?')[1]})})

3、对于 楼层图片区域的 image 标签的父标签都改成 navigator

<!-- 楼层图片区域 -->
<view class="floor-img-box"><!-- 左侧大图片的盒子 --><navigator class="left-img-box" :url="item.product_list[0].url"><image :src="item.product_list[0].image_src" :style="{width: item.product_list[0].image_width + 'rpx'}" mode="widthFix"></image></navigator><!-- 右侧 4 个小图片的盒子 --><view class="right-img-box"><navigator class="right-img-item" v-for="(item2, i2) in item.product_list" :key="i2" v-if="i2 !== 0" :url="item2.url"><image :src="item2.image_src" mode="widthFix" :style="{width: item2.image_width + 'rpx'}"></image></navigator></view>
</view>

2.16 分支的合并与提交

git add .
git commit -m "完成了 home 开发"
# 将 home 分支 推送到远程仓库
git push -u origin home
# 将 home分支合并到 master 分支上
git checkout master
git merge home# 删除本地 home 分支
git branch -d home# 把 写完的代码,推送到远程仓库的主分支上
git push

3、分类页面

3.1 创建 cate 分支

git checkout -b cate

3.2 实现分类页面滑动区域的左右布局

3.3 动态设置 scroll-view 组件的高度

 export default {data() {return {// 当前设备可用的高度wh: 0,};},onLoad() {const sysInfo = uni.getSystemInfoSync()console.log(sysInfo);// sysInfo 有个属性 windowHeight 属性,就是 可用的高度this.wh = sysInfo.windowHeight}}

3.4 美化左侧 scroll-view中item项的样式

3.5 获取分类列表数据

 export default {data() {return {// 当前设备可用的高度wh: 0,// 分类数据列表cateList: []};},onLoad() {const sysInfo = uni.getSystemInfoSync()console.log(sysInfo);// sysInfo 有个属性 windowHeight 属性,就是 可用的高度this.wh = sysInfo.windowHeight// 获取分类列表数据this.getCateList()},methods: {async getCateList() {// 发起请求const {data: res} = await uni.$http.get('/api/public/v1/categories')if (res.meta.status !== 200) return uni.$showMsg()// 转存数据this.cateList = res.message}}}

3.6 动态渲染左侧一级分类列表

         <!-- 左侧的滚动视图区域 --><scroll-view class="left-scroll-view" scroll-y :style="{height: wh + 'px'}"><block v-for="(item,i) in cateList" :key="i"><view :class="['left-scroll-view-item', i=== active ? 'active' : '']" @click="activeChanged(i)">{{item.cat_name}}</view></block></scroll-view>

动态绑定类名

3.7 定义二级分类的数据列表

在初始化的时候,我们可以 把 默认第一项的children 给 cateLevel2
在监听 点击事件,根据 传过来的索引,再根据 cateList 动态获取值

this.cateLevel2 = res.message[0].childrenthis.cateLevel2 = this.cateList[i].children

3.8 动态渲染右侧二级目录

         <!-- 右侧的滚动视图区域 --><scroll-view class="right-scroll-view" scroll-y :style="{height: wh + 'px'}"><view class="cate-lv2" v-for="(item2, i2) in cateLevel2" :key="i2"><view class="cate-lv2-title">/ {{item2.cat_name}} /</view></view></scroll-view>

3.9 动态渲染右侧三级分类

    <!-- 动态渲染三级分类的列表数据 --><view class="cate-lv3-list"><!-- 三级分类 Item 项 --><view class="cate-lv3-item" v-for="(item3, i3) in item2.children" :key="i3"><!-- 图片 --><image :src="item3.cat_icon"></image><!-- 文本 --><text>{{item3.cat_name}}</text></view></view>
.cate-lv3-list {display: flex;flex-wrap: wrap;.cate-lv3-item {width: 33.33%;margin-bottom: 10px;display: flex;flex-direction: column;align-items: center;image {width: 60px;height: 60px;}text {font-size: 12px;}}
}

3.10 切换一级分类后重置滚动条位置

1、在 data 中 定义 scrollTop: 0
2、

<scroll-view class="right-scroll-view" scroll-y :style="{height: wh + 'px'}" :scroll-top="scrollTop"></scroll-view>

3、

// 选中项改变的事件处理函数
activeChanged(i) {this.active = ithis.cateLevel2 = this.cateList[i].children//this.scrollTop = 0  前后滚动位置是一样的,不会进行切换this.scrollTop = this.scrollTop === 0 ? 1 : 0}

3.11 点击三级分类 跳转到商品列表详情页面

<view class="cate-lv3-item" v-for="(item3, i3) in item2.children" :key="i3" @click="gotoGoodsList(item3)"><image :src="item3.cat_icon"></image><text>{{item3.cat_name}}</text>
</view>// 点击三级分类项跳转到商品列表页面
gotoGoodsList(item3) {uni.navigateTo({url: '/subpkg/goods_list/goods_list?cid=' + item3.cat_id})
}

3.12 提交

4、自定义搜索组件

4.1 相关功能

  1. 自定义组件
  2. 搜索页面
  3. 搜索历史

4.2 新建分支

git checkout -b search

4.3 新建自定义组件

在根目录新建 components 文件夹
然后 右击 选择新建组件,然后就可以在任意位置使用了

4.4 渲染自定义组件的基本结构

<template><view><view class="my-search-container"><!-- 使用 view 组件模拟 input 输入框的样式 --><view class="my-search-box"><uni-icons type="search" size="17"></uni-icons><text class="placeholder">搜索</text></view></view></view>
</template><script>export default {name: "my-search",data() {return {};}}
</script><style lang="scss">.my-search-container {background-color: #c00000;height: 50px;padding: 0 10px;display: flex;align-items: center;}.my-search-box {height: 36px;background-color: #ffffff;border-radius: 15px;width: 100%;display: flex;align-items: center;justify-content: center;.placeholder {font-size: 15px;margin-left: 5px;}}
</style>

4.5 解决 cate 分类页面的 scroll-view 高度问题

onLoad() {const sysInfo = uni.getSystemInfoSync()// 可用高度 = 屏幕高度 - navigationBar高度 - tabBar高度 - 自定义的search组件高度this.wh = sysInfo.windowHeight - 50
}

4.6 采用props 默认值

props: {// 背景颜色bgcolor: {type: String,default: '#C00000'},// 圆角尺寸radius: {type: Number,// 单位是 pxdefault: 18}
}

4.7 为自定义组件封装click 事件

你在父组件中,给自定义组件绑定 点击 事件,没有任何用,因为你在自定义组件中,没有封装这个点击事件

  1. 我们可以 给 自定义组件的 最外面的 view 标签,绑定点击事件,,view 支持点击事件
  2. 在 自定义组件 view 的click 事件处理程序中,加入 this.$emit(‘事件名称’) 即可在点击的时候,即触发父组件 给 自定义组件添加的点击事件,也可以触发自定义组件 view 的click 事件
  3. 当我们 鼠标点击 这个自定义组件的时候,先触发,自定义组件的事件,在触发暴露给父组件的 点击事件
# 自定义组件
<view class="my-search-box" :style="{'border-radius': radius + 'px'}" @click="searchBoxHandler"><uni-icons type="search" size="17"></uni-icons><text class="placeholder">搜索</text>
</view>methods:{searchBoxHandle(){console.log('自定义组件');// 触发外界通过 @click 绑定的click 事件处理函数this.$emit('click')// 如果这里修改成 myclick 外面也要修改成 @myclick="gotoSearch"// 类似于 vue 的 子传父}}#父组件
<my-search @click="gotoSearch"></my-search>methods: {gotoSearch(){console.log('父组件的click');},}

3.8 完成跳转到 搜素页面

在 subpkg 新建一个 页面

methods: {// 跳转到分包中的搜索页面gotoSearch() {uni.navigateTo({url: '/subpkg/search/search'})}
}

4.9 自定义组件,实现首页搜索组件的吸附效果

在首页中,实现 自定义搜索组件的固定定位

<!-- 使用自定义的搜索组件 -->
<view class="search-box"><my-search @click="gotoSearch"></my-search>
</view>gotoSearch() {uni.navigateTo({url: '/subpkg/search/search'})
}.search-box {// 设置定位效果为“吸顶”position: sticky;// 吸顶的“位置”top: 0;// 提高层级,防止被轮播图覆盖z-index: 999;
}

5、搜索建议和搜索历史

5.1 渲染搜索页面的基本结构

搜索框的结构我们采用 uni-ui 提供的样式 https://uniapp.dcloud.io/component/README?id=uniui
uni-ui的搜索栏 api

 <view class="search-box"><!-- 使用 uni-ui 提供的搜索组件 --><uni-search-bar :focus="true" bgColor="#ffffff" @input="input" :radius="100" cancelButton="none"></uni-search-bar></view>

找到根目录下的 uni_modules => uni-search-bar => components => uni-search-bar => uni-search-bar.vue
把.uni-searchbar 这个类,添加背景颜色 #c00000

实现搜索框的吸顶

.search-box {position: sticky;top: 0;z-index: 999;
}

5.2 实现搜索框 自动获取焦点

修改 components -> uni-search-bar -> uni-search-bar.vue 组件,把 data 数据中的 show 和 showSync 的值,从默认的 false 改为 true 即可:

data() {return {show: true,showSync: true,searchVal: ""}
}

5.3 实现搜索框的 防抖处理

 export default {data() {return {searchValue: '',// 延迟期 的返回值timer: null,// 搜索的关键词kw: ''}},methods: {input(e) {clearTimeout(this.timer)this.timer = setTimeout(() => {this.kw = e}, 500)}}}

5.4 根据搜索关键词搜索建议列表

1、再 data 定义 数据节点,存储 搜索建议的列表

data() {return {// 搜索结果列表searchResults: []}
}

2、再防抖的延迟器 里面调用这个方法
3、在methods 定义这个方法

// 根据搜索关键词,搜索商品建议列表
async getSearchList() {// 判断关键词是否为空if (this.kw === '') {this.searchResults = []return}// 发起请求,获取搜索建议列表const { data: res } = await uni.$http.get('/api/public/v1/goods/qsearch', { query: this.kw })if (res.meta.status !== 200) return uni.$showMsg()this.searchResults = res.message
}

5.5 渲染搜索建议

5.6 美化搜索建议列表的UI结构

     <!-- 搜索建议列表 --><view class="sugg-list"><view class="sugg-item" v-for="(item, i) in searchResults" :key="i" @click="gotoDetail(item.goods_id)"><view class="goods-name">{{item.goods_name}}</view><uni-icons type="arrowright" size="16"></uni-icons></view></view>
.sugg-list {padding: 0 5px;.sugg-item {font-size: 12px;padding: 13px 0;border-bottom: 1px solid #efefef;display: flex;align-items: center;justify-content: space-between;.goods-name {// 文字不允许换行(单行文本)white-space: nowrap;// 溢出部分隐藏overflow: hidden;// 文本溢出后,使用 ... 代替text-overflow: ellipsis;margin-right: 3px;}}}

5.7 点击搜索 item 项导航到商品详情页

gotoDetail(goods_id) {uni.navigateTo({// 指定详情页面的 URL 地址,并传递 goods_id 参数url: '/subpkg/goods_detail/goods_detail?goods_id=' + goods_id})
}

5.8 渲染搜索历史记录的基本结构

5.9 美化搜索历史区域的样式

1、在 data 中定义搜索历史的 加数据

data() {return {// 搜索关键词的历史记录historyList: ['a', 'app', 'apple']}
}

2、渲染搜索历史区域的 UI结构

<!-- 搜索历史 -->
<view class="history-box"><!-- 标题区域 --><view class="history-title"><text>搜索历史</text><uni-icons type="trash" size="17"></uni-icons></view><!-- 列表区域 --><view class="history-list"><uni-tag :text="item" v-for="(item, i) in historyList" :key="i"></uni-tag></view>
</view>

3、美化搜索历史区域的样式

.history-box {padding: 0 5px;.history-title {display: flex;justify-content: space-between;align-items: center;height: 40px;font-size: 13px;border-bottom: 1px solid #efefef;}.history-list {display: flex;flex-wrap: wrap;.uni-tag {margin-top: 5px;margin-right: 5px;}}
}

5.10 实现搜索建议和搜索历史的按需展示

  1. 当搜索结构列表的长度 不为 0 的时候,要展示搜索建议区域,隐藏搜索历史
  2. 当搜索结构的长度 =0 的时候, 需要展示搜索历史,隐藏搜索建议
<!-- 搜索建议列表 -->
<view class="sugg-list" v-if="searchResults.length !== 0"><!-- 省略其它代码... -->
</view><!-- 搜索历史 -->
<view class="history-box" v-else><!-- 省略其它代码... -->
</view>

5.11 将搜索关键词存入 data节点

methods: {// 根据搜索关键词,搜索商品建议列表async getSearchList() {// 省略其它不必要的代码...// 1. 查询到搜索建议之后,调用 saveSearchHistory() 方法保存搜索关键词this.saveSearchHistory()},// 2. 保存搜索关键词的方法saveSearchHistory() {// 2.1 直接把搜索关键词 push 到 historyList 数组中this.historyList.push(this.kw)}
}

5.12 解决关键词前后顺序的问题

1、data 中的 historyList 不做任何修改,以然使用 push 进行 末尾添加
2、定义一个计算属性 historys 将 historyList 数组 reverse 反转之后

computed: {historys() {// 注意:由于数组是引用类型,所以不要直接基于原数组调用 reverse 方法,以免修改原数组中元素的顺序// 而是应该新建一个内存无关的数组,再进行 reverse 反转return [...this.historyList].reverse()}
}

3、页面中渲染搜索关键词的时候,不再使用 data 中的 historyList,而是使用计算属性 historys

5.13 解决关键词重复的问题

// 保存搜索关键词为历史记录
saveSearchHistory() {// this.historyList.push(this.kw)// 1. 将 Array 数组转化为 Set 对象const set = new Set(this.historyList)// 2. 调用 Set 对象的 delete 方法,移除对应的元素set.delete(this.kw)// 3. 调用 Set 对象的 add 方法,向 Set 中添加元素set.add(this.kw)// 4. 将 Set 对象转化为 Array 数组this.historyList = Array.from(set)
}

5.14 将搜素历史记录持久化存储到本地

// 保存搜索关键词为历史记录
saveSearchHistory() {const set = new Set(this.historyList)set.delete(this.kw)set.add(this.kw)this.historyList = Array.from(set)// 调用 uni.setStorageSync(key, value) 将搜索历史记录持久化存储到本地uni.setStorageSync('kw', JSON.stringify(this.historyList))
}onLoad() {this.historyList = JSON.parse(uni.getStorageSync('kw') || '[]')
}

5.15 清空搜索历史记录

<uni-icons type="trash" size="17" @click="cleanHistory"></uni-icons>
// 清空搜索历史记录
cleanHistory() {// 清空 data 中保存的搜索历史this.historyList = []// 清空本地存储中记录的搜索历史uni.setStorageSync('kw', '[]')
}

5.16 点击搜索历史 跳转到 商品列表页面

<uni-tag :text="item" v-for="(item, i) in historys" :key="i" @click="gotoGoodsList(item)"></uni-tag>
// 点击跳转到商品列表页面
gotoGoodsList(kw) {uni.navigateTo({url: '/subpkg/goods_list/goods_list?query=' + kw})
}

6、商品列表功能实现

6.1 商品列表功能并创建分支

  1. 下拉刷新
  2. 触底加载
  3. 列表渲染
  4. 跳转到详情页

6.2 创建

git checkout -b goodslist

6.3 定义请求参数对象

1、为了方便,在data里面定义一个请求参数对象

data() {return {// 请求参数对象queryObj: {// 查询关键词query: '',// 商品分类Idcid: '',// 页码值pagenum: 1,// 每页显示多少条数据pagesize: 10}}
}

2、在页面跳转的时候就得 赋值

onLoad(options) {// 将页面参数转存到 this.queryObj 对象中this.queryObj.query = options.query || ''this.queryObj.cid = options.cid || ''
}

6.4 获取商品列表数据

 export default {data() {return {// 请求参数对象queryObj: {// 查询关键词query: '',// 商品分类Idcid: '',// 页码值pagenum: 1,// 每页显示多少条数据pagesize: 10},// 商品列表的数据goodsList: [],// 总数量,用来实现分页total: 0}},onLoad(options) {// 将页面参数转存到 this.queryObj 对象中this.queryObj.query = options.query || ''this.queryObj.cid = options.cid || ''// 调用获取商品列表数据的方法this.getGoodsList()},methods: {// 获取商品列表数据的方法async getGoodsList() {// 发起请求const {data: res} = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)if (res.meta.status !== 200) return uni.$showMsg()// 为数据赋值this.goodsList = res.message.goodsthis.total = res.message.total}}}

6.5 定义商品列表页面的UI结构

6.6 美化结构

6.7 吧商品的item项,修改成一个 自定义组件

1、创建一个 my-item 自定义组件

<template><view class="goods-item"><!-- 商品左侧图片区域 --><view class="goods-item-left"><image :src="goods.goods_small_logo || defaultPic" class="goods-pic"></image></view><!-- 商品右侧信息区域 --><view class="goods-item-right"><!-- 商品标题 --><view class="goods-name">{{goods.goods_name}}</view><view class="goods-info-box"><!-- 商品价格 --><view class="goods-price">¥{{goods.goods_price}}</view></view></view></view>
</template><script>export default {// 定义 props 属性,用来接收外界传递到当前组件的数据props: {// 商品的信息对象goods: {type: Object,defaul: {},},},data() {return {// 默认的空图片defaultPic: 'https://img3.doubanio.com/f/movie/8dd0c794499fe925ae2ae89ee30cd225750457b4/pics/movie/celebrity-default-medium.png',}},}
</script><style lang="scss">.goods-item {display: flex;padding: 10px 5px;border-bottom: 1px solid #f0f0f0;.goods-item-left {margin-right: 5px;.goods-pic {width: 100px;height: 100px;display: block;}}.goods-item-right {display: flex;flex-direction: column;justify-content: space-between;.goods-name {font-size: 13px;}.goods-price {font-size: 16px;color: #c00000;}}}
</style>

2、goodsList 组件

         <block v-for="(item, i) in goodsList" :key="i"><!-- 为 my-goods 组件动态绑定 goods 属性的值 --><my-goods :goods="item"></my-goods></block>

6.8 使用过滤器处理商品价格

1、在my-goods 组件中,和data节点评级,声明 filters 节点

filters: {// 把数字处理为带两位小数点的数字tofixed(num) {return Number(num).toFixed(2)}
}

2、在 渲染模板中

<!-- 商品价格 -->
<view class="goods-price">¥{{goods.goods_price | tofixed}}</view>

6.9 上拉加载更多

1、打开 项目 根目录的 page.json 配置文件,

 "subPackages": [{"root": "subpkg","pages": [{"path": "goods_detail/goods_detail"}, {"path": "goods_list/goods_list","style": {"onReachBottomDistance": 150}}, {"path": "search/search","style": {}}]}],

2、在 goodList 页面中,和data 评级,声明 onReachBottom 事件处理函数,用来监听页面的上拉触底行为

// 触底的事件
onReachBottom() {// 让页码值自增 +1this.queryObj.pagenum += 1// 重新获取列表数据this.getGoodsList()
}

3、在 methods 中 的 getGoodsList 函数,成功后,进行新旧数据拼接

// 获取商品列表数据的方法
async getGoodsList() {// 发起请求const { data: res } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)if (res.meta.status !== 200) return uni.$showMsg()// 为数据赋值:通过展开运算符的形式,进行新旧数据的拼接this.goodsList = [...this.goodsList, ...res.message.goods]this.total = res.message.total
}

6.10 定义节流阀,节流

1、在 data 中定义 isloading 节流阀如下:

data() {return {// 是否正在请求数据isloading: false}
}

2、修改 getGoodsList 方法

// 获取商品列表数据的方法
async getGoodsList() {// ** 打开节流阀this.isloading = true// 发起请求const { data: res } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)// ** 关闭节流阀this.isloading = false// 省略其它代码...
}

3、在 触底事件处理函数中,根据节流阀状态,来决定是否发起请求

// 触底的事件
onReachBottom() {// 判断是否正在请求其它数据,如果是,则不发起额外的请求if (this.isloading) returnthis.queryObj.pagenum += 1this.getGoodsList()
}

6.11 实现下拉刷新的效果

当前的页码值 * 每页显示多少条数据 >= 总数条数
pagenum * pagesize >= total

// 触底的事件
onReachBottom() {// 判断是否还有下一页数据if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total) return uni.$showMsg('数据加载完毕!')// 判断是否正在请求其它数据,如果是,则不发起额外的请求if (this.isloading) returnthis.queryObj.pagenum += 1this.getGoodsList()
}

6.12 下拉刷新

1、在 page.json 中

"subPackages": [{"root": "subpkg","pages": [{"path": "goods_detail/goods_detail","style": {}}, {"path": "goods_list/goods_list","style": {"onReachBottomDistance": 150,"enablePullDownRefresh": true,"backgroundColor": "#F8F8F8"}}, {"path": "search/search","style": {}}]
}]

2、监听 下拉刷新事件

// 下拉刷新的事件
onPullDownRefresh() {// 1. 重置关键数据this.queryObj.pagenum = 1this.total = 0this.isloading = falsethis.goodsList = []// 2. 重新发起请求this.getGoodsList(() => uni.stopPullDownRefresh())
}

3、修改 getGoodsList 事件

// 获取商品列表数据的方法
async getGoodsList(cb) {this.isloading = trueconst { data: res } = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)this.isloading = false// 只要数据请求完毕,就立即按需调用 cb 回调函数cb && cb()if (res.meta.status !== 200) return uni.$showMsg()this.goodsList = [...this.goodsList, ...res.message.goods]this.total = res.message.total
}

6.13 点击商品 item 项 跳转到详情页面

注意要把循环时的,block 组件修改为view组件
因为block 组件只是起一个占位的作用,并不会渲染在DOM上

<view class="goods-list"><view v-for="(item, i) in goodsList" :key="i" @click="gotoDetail(item)"><!-- 为 my-goods 组件动态绑定 goods 属性的值 --><my-goods :goods="item"></my-goods></view>
</view>
// 点击跳转到商品详情页面
gotoDetail(item) {uni.navigateTo({url: '/subpkg/goods_detail/goods_detail?goods_id=' + item.goods_id})
}

7、商品详情功能实现

7.1 创建 goodsdetail 分支

git checkout -b goodsdetail

在微信小程序创建 编译模式,参数:goods_id=395

7.2 添加 编译模式

7.3 获取商品详情的数据

1、在data 中定义 goods_info 商品详情对象
2、在 onload 中 获取商品的 id 并调用方法
3、在 methods 中 定义方法

methods: {// 定义请求商品详情数据的方法async getGoodsDetail(goods_id) {const { data: res } = await uni.$http.get('/api/public/v1/goods/detail', { goods_id })if (res.meta.status !== 200) return uni.$showMsg()// 为 data 中的数据赋值this.goods_info = res.message}
}

7.4 渲染轮播图区域

<!-- 轮播图区域 -->
<swiper :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000" :circular="true"><swiper-item v-for="(item, i) in goods_info.pics" :key="i"><image :src="item.pics_big"></image></swiper-item>
</swiper>
swiper {height: 750rpx;image {width: 100%;height: 100%;}
}

7.5 实现轮播图的大图预览效果

图片预览API

<swiper-item v-for="(item, i) in goods_info.pics" :key="i"><!-- 把当前点击的图片的索引,传递到 preview() 处理函数中 --><image :src="item.pics_big" @click="preview(i)"></image>
</swiper-item>
// 实现轮播图的预览效果
preview(i) {// 调用 uni.previewImage() 方法预览图片uni.previewImage({// 预览时,默认显示图片的索引current: i,// 所有图片 url 地址的数组urls: this.goods_info.pics.map(x => x.pics_big)})
}

7.6 渲染商品信息区域的 UI结构

<!-- 商品信息区域 -->
<view class="goods-info-box"><!-- 商品价格 --><view class="price">¥{{goods_info.goods_price}}</view><!-- 信息主体区域 --><view class="goods-info-body"><!-- 商品名称 --><view class="goods-name">{{goods_info.goods_name}}</view><!-- 收藏 --><view class="favi"><uni-icons type="star" size="18" color="gray"></uni-icons><text>收藏</text></view></view><!-- 运费 --><view class="yf">快递:免运费</view>
</view>
// 商品信息区域的样式
.goods-info-box {padding: 10px;padding-right: 0;.price {color: #c00000;font-size: 18px;margin: 10px 0;}.goods-info-body {display: flex;justify-content: space-between;.goods-name {font-size: 13px;padding-right: 10px;}// 收藏区域.favi {width: 120px;font-size: 12px;display: flex;flex-direction: column;justify-content: center;align-items: center;border-left: 1px solid #efefef;color: gray;}}// 运费.yf {margin: 10px 0;font-size: 12px;color: gray;}
}

7.7 美化商品信息区域的样式

7.8 使用rich-text 组件渲染 HTML内容

<!-- 商品详情信息 -->
<rich-text :nodes="goods_info.goods_introduce"></rich-text>

7.9 解决商品图文中图片底部空白间隙的问题

把服务器传过来来的 goods_info.goods_introduce 节点的数据进行改造,给图片标签设置一个 display:block 就可以

// 使用字符串的 replace() 方法,为 img 标签添加行内的 style 样式,从而解决图片底部空白间隙的问题res.message.goods_introduce = res.message.goods_introduce.replace(/<img /g, '<img style="display:block;" ')this.goods_info = res.message

7.10 解决 webp格式的图片在 ios 设备无法显示

// 使用字符串的 replace() 方法,将 webp 的后缀名替换为 jpg 的后缀名res.message.goods_introduce = res.message.goods_introduce.replace(/<img /g, '<img style="display:block;" ').replace(/webp/g, 'jpg')

7.11 解决 商品价格闪烁的问题

在商品详情数据请求回来之前,data 中 goods_info 的值为(),因为初次渲染页面时,会导致商品价格、商品名称 灯闪烁的问题

解决方案:判断 goods_info.goods_name 属性的值是否存在,从而使用 v-if 指令控制页面的显示与隐藏

<template><view v-if="goods_info.goods_name"><!-- 省略其它代码 --></view>
</template>

7.12 渲染商品导航区域的UI结构

值得就是 店铺、购物车、加入购物车、立即购买

我们采用 uni-ui 提供的 GoodsNav 组件来实现商品导航区域的效果

7.13 自定义导航区域的按钮信息

1、在data 中定义如下节点

data() {return {// 商品详情对象goods_info: {},// 左侧按钮组的配置对象options: [{icon: 'shop',text: '店铺'}, {icon: 'cart',text: '购物车',info: 2}],// 右侧按钮组的配置对象buttonGroup: [{text: '加入购物车',backgroundColor: '#ff0000',color: '#fff'},{text: '立即购买',backgroundColor: '#ffa200',color: '#fff'}]}
}

2、在 页面中使用

<!-- 商品导航组件 -->
<view class="goods_nav"><!-- fill 控制右侧按钮的样式 --><!-- options 左侧按钮的配置项 --><!-- buttonGroup 右侧按钮的配置项 --><!-- click 左侧按钮的点击事件处理函数 --><!-- buttonClick 右侧按钮的点击事件处理函数 --><uni-goods-nav :fill="true" :options="options" :buttonGroup="buttonGroup" @click="onClick" @buttonClick="buttonClick" />
</view>

3、美化组件

.goods-detail-container {// 给页面外层的容器,添加 50px 的内padding,// 防止页面内容被底部的商品导航组件遮盖padding-bottom: 50px;
}.goods_nav {// 为商品导航组件添加固定定位position: fixed;bottom: 0;left: 0;width: 100%;
}

7.14 点击购物车 按钮 跳转到 购物车页面

         onClick(e) {console.log(e);// {content: {icon: "shop", text: "店铺"} , index: 0}if (e.content.text === '购物车') {// 切换到购物车页面uni.switchTab({url: '/pages/cart/cart'})}}

8 加入购物车功能实现

8.1 创建分支

git checkout -b cart

8.2 配置 vuex

1、在项目 根目录中创建 store 文件夹 存放 vuex
2、在 store 目录上右击,创建 js文件 ,store.js
3、在 store.js 中

// 1. 导入 Vue 和 Vuex
import Vue from 'vue'
import Vuex from 'vuex'// 2. 将 Vuex 安装为 Vue 的插件
Vue.use(Vuex)// 3. 创建 Store 的实例对象
const store = new Vuex.Store({// TODO:挂载 store 模块modules: {},
})// 4. 向外共享 Store 的实例对象
export default store

4、在main.js 中

// 1. 导入 store 的实例对象
import store from './store/store.js'// 省略其它代码...const app = new Vue({...App,// 2. 将 store 挂载到 Vue 实例上store,
})
app.$mount()

8.3 创建购物车的 store 模块

在 cart.js 中 初始化 数据

export default {// 为当前模块开启命名空间namespaced: true,// 模块的 state 数据state: {// 购物车的数组,用来存储购物车中每个商品的信息对象// 每个商品的信息对象,都包含如下 6 个属性:// { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }cart: [],},// 模块的 mutations 方法mutations: {},// 模块的 getters 属性getters: {},
}
# 在 store/store.js 模块中,挂在购物车的 vuex 模块
import Vue from 'vue'
import Vuex from 'vuex'
// 1. 导入购物车的 vuex 模块
import moduleCart from './cart.js'Vue.use(Vuex)const store = new Vuex.Store({// TODO:挂载 store 模块modules: {// 2. 挂载购物车的 vuex 模块,模块内成员的访问路径被调整为 m_cart,例如://    购物车模块中 cart 数组的访问路径是 m_cart/cartm_cart: moduleCart,},
})export default store

8.4 在商品详情页中使用 store中的数据

在 goods_detail.vue 页面

// 从 vuex 中按需导出 mapState 辅助方法
import { mapState } from 'vuex'export default {computed: {// 调用 mapState 方法,把 m_cart 模块中的 cart 数组映射到当前页面中,作为计算属性来使用// ...mapState('模块的名称', ['要映射的数据名称1', '要映射的数据名称2'])...mapState('m_cart', ['cart']),},// 省略其它代码...
}

2、直接使用

<!-- 运费 -->
<view class="yf">快递:免运费 -- {{cart.length}}</view>

8.5 在 cart.js 中 mutations 中定义 加入到购物车方法

 mutations: {addToCart(state, goods) {// state 就是 state 的 数据对象// goods 是要到购物车的,商品数据对象// 判断购物车有没有 拽哥商品// find 判断 这个数组里面有没有符合条件的,如果有返回 x 本身,没有返回 undefindconst findResult = state.cart.find(x => x.goods_id === goods.goods_id)if (!findResult) {state.cart.push(goods)} else {findResult.goods_count++}},},

8.6 实现加入购物车功能

1、在 商品详情页面 导入这个方法

// 按需导入 mapMutations 这个辅助方法
import { mapMutations } from 'vuex'export default {methods: {// 把 m_cart 模块中的 addToCart 方法映射到当前页面使用...mapMutations('m_cart', ['addToCart']),},
}

2、给组件 uni-goods-nav 绑定 @buttonClick = “buttonClick”

// 右侧按钮的点击事件处理函数
buttonClick(e) {// 1. 判断是否点击了 加入购物车 按钮if (e.content.text === '加入购物车') {// 2. 组织一个商品的信息对象const goods = {goods_id: this.goods_info.goods_id,       // 商品的Idgoods_name: this.goods_info.goods_name,   // 商品的名称goods_price: this.goods_info.goods_price, // 商品的价格goods_count: 1,                           // 商品的数量goods_small_logo: this.goods_info.goods_small_logo, // 商品的图片goods_state: true                         // 商品的勾选状态}// 3. 通过 this 调用映射过来的 addToCart 方法,把商品信息对象存储到购物车中this.addToCart(goods)}
}

8.7 动态统计购物车商品的总数量

1、在 cart.js 模块中,在 getters 节点下定义一个 total 方法,用来统计购物车中商品的总数量:

// 模块的 getters 属性
getters: {// 统计购物车中商品的总数量total(state) {let c = 0// 循环统计商品的数量,累加到变量 c 中state.cart.forEach(goods => c += goods.goods_count)return c}
}

2、

// 按需导入 mapGetters 这个辅助方法
import { mapGetters } from 'vuex'export default {computed: {// 把 m_cart 模块中名称为 total 的 getter 映射到当前页面中使用...mapGetters('m_cart', ['total']),},
}

3、通过 watch 侦听器,监听计算属性 total 值的变化,从而动态为购物车按钮的徽标赋值:

export default {watch: {// 1. 监听 total 值的变化,通过第一个形参得到变化后的新值total(newVal) {// 2. 通过数组的 find() 方法,找到购物车按钮的配置对象const findResult = this.options.find((x) => x.text === '购物车')if (findResult) {// 3. 动态为购物车按钮的 info 属性赋值findResult.info = newVal}},},
}

8.8 持久化 存储购物车中的商品

1、在 cart.js 模块中,声明一个叫做 saveToStorage 的 mutations 方法,此方法负责将购物车中的数据持久化存储到本地:

// 将购物车中的数据持久化存储到本地
saveToStorage(state) {uni.setStorageSync('cart', JSON.stringify(state.cart))
}

2、修改 mutations 节点中的 addToCart 方法,在处理完商品信息后,调用步骤 1 中定义的 saveToStorage 方法:

addToCart(state, goods) {// 根据提交的商品的Id,查询购物车中是否存在这件商品// 如果不存在,则 findResult 为 undefined;否则,为查找到的商品信息对象const findResult = state.cart.find(x => x.goods_id === goods.goods_id)if (!findResult) {// 如果购物车中没有这件商品,则直接 pushstate.cart.push(goods)} else {// 如果购物车中有这件商品,则只更新数量即可findResult.goods_count++}// 通过 commit 方法,调用 m_cart 命名空间下的 saveToStorage 方法this.commit('m_cart/saveToStorage')
}

3、修改 cart.js 模块中的 state 函数,读取本地存储的购物车数据,对 cart 数组进行初始化

// 模块的 state 数据
state: () => ({// 购物车的数组,用来存储购物车中每个商品的信息对象// 每个商品的信息对象,都包含如下 6 个属性:// { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }cart: JSON.parse(uni.getStorageSync('cart') || '[]')
}),

8.9 优化商品详情页的 total 侦听器

使用普通函数的形式定义的 watch 侦听器,在页面首次加载后不会被调用。

watch: {// 定义 total 侦听器,指向一个配置对象total: {// handler 属性用来定义侦听器的 function 处理函数handler(newVal) {const findResult = this.options.find(x => x.text === '购物车')if (findResult) {findResult.info = newVal}},// immediate 属性用来声明此侦听器,是否在页面初次加载完毕后立即调用immediate: true}
}

8.10 为 tabbar 设置 徽标

1、把 Store 中的 total 映射到 cart.vue 中使用:

// 按需导入 mapGetters 这个辅助方法
import { mapGetters } from 'vuex'export default {data() {return {}},computed: {// 将 m_cart 模块中的 total 映射为当前页面的计算属性...mapGetters('m_cart', ['total']),},
}

2、在页面刚显示出来的时候,立即调用 setBadge 方法,为 tabBar 设置数字徽标

onShow() {// 在页面刚展示的时候,设置数字徽标this.setBadge()
}

3、methods 节点中,声明 setBadge 方法如下,通过uni.setTabBarBadge() 为 tabBar 设置数字徽标

methods: {setBadge() {// 调用 uni.setTabBarBadge() 方法,为购物车设置右上角的徽标uni.setTabBarBadge({index: 2, // 索引text: this.total + '' // 注意:text 的值必须是字符串,不能是数字})}
}

8.11 将设置 tabbar 徽标的代码抽离

除了要在 cart.vue 页面中设置购物车的数字徽标,还需要在其它 3 个 tabBar 页面中,为购物车设置数字徽标。
此时可以使用 Vue 提供的 mixins 特性,提高代码的可维护性。

1、在项目根目录中新建 mixins 文件夹,并在 mixins 文件夹之下新建 tabbar-badge.js 文件,用来把设置 tabBar 徽标的代码封装为一个 mixin 文件:

import { mapGetters } from 'vuex'// 导出一个 mixin 对象
export default {computed: {...mapGetters('m_cart', ['total']),},onShow() {// 在页面刚展示的时候,设置数字徽标this.setBadge()},methods: {setBadge() {// 调用 uni.setTabBarBadge() 方法,为购物车设置右上角的徽标uni.setTabBarBadge({index: 2,text: this.total + '', // 注意:text 的值必须是字符串,不能是数字})},},
}

2、修改 home.vue,cate.vue,cart.vue,my.vue 这 4 个 tabBar 页面的源代码,分别导入 @/mixins/tabbar-badge.js 模块并进行使用

// 导入自己封装的 mixin 模块
import badgeMix from '@/mixins/tabbar-badge.js'export default {// 将 badgeMix 混入到当前的页面中进行使用mixins: [badgeMix],// 省略其它代码...
}

9、购物车页面

9.1 需求

  1. 购物车渲染
  2. 全选,单选
  3. 收货地址
  4. 商品累加
  5. 结算商品数量
  6. 总价格

9.2 创建购物车页面的编译模式

cart

9.3 渲染商品列表的标题区域

cart.vue

     <!-- 购物车商品列表的标题区域 --><view class="cart-title"><!-- 左侧的图标 --><uni-icons type="shop" size="18"></uni-icons><!-- 描述文本 --><text class="cart-title-text">购物车</text></view>
 .cart-title {height: 40px;display: flex;align-items: center;font-size: 14px;padding-left: 5px;border-bottom: 1px solid #efefef;.cart-title-text {margin-left: 10px;}}

9.4 渲染商品列表的基本结构

# 到入  mapState
import { mapState } from 'vuex'computed : {// 将 m_cart 模块中的 cart 数组映射到当前页面中使用...mapState('m_cart',['cart'])
}
<!-- 商品列表区域 -->
<block v-for="(goods, i) in cart" :key="i"><my-goods :goods="goods"></my-goods>
</block>

9.5 为 my-goods 组件封装 radio 勾选状态

1、打开 my-goods.vue 组件的源代码,为商品左侧图片区域添加 radio 组件

<!-- 商品左侧图片区域 -->
<view class="goods-item-left"><radio checked color="#C00000"></radio><image :src="goods.goods_small_logo || defaultPic" class="goods-pic"></image>
</view>

2、给类名为 goods-item-left 的 view 组件添加样式,实现 radio 组件和 image 组件的左右布局

.goods-item-left {margin-right: 5px;display: flex;justify-content: space-between;align-items: center;.goods-pic {width: 100px;height: 100px;display: block;}
}

3、添加 一个 showRadio 的 props 属性,来控制当前组件是否显示radio 组件

     props: {// 商品的信息对象goods: {type: Object,defaul: {},},// 书否展示图片左侧的 radioshowRadio: {type: Boolean,default: false}},

4、使用 v-if 指令控制 radio 组件的按需展示

<radio checked color="#C00000" v-if="showRadio"></radio>

5、在 cart.vue 页面中的商品列表区域,指定 :show-radio=“true” 属性,从而显示 radio 组件
6、修改 my-goods.vue 组件,动态为 radio 绑定选中状态

<view class="goods-item-left"><!-- 存储在购物车中的商品,包含 goods_state 属性,表示商品的勾选状态 --><radio :checked="goods.goods_state" color="#C00000" v-if="showRadio"></radio><image :src="goods.goods_small_logo || defaultPic" class="goods-pic"></image>
</view>

9.6 通过 props 属性控制 radio 显示

9.7 动态绑定 radio 的 checked 的值

9.8 为 my-goods 组件封装 radio-change 事件的实现思路

循环 渲染 my_gooods 组件,购物车有几个商品就循环渲染几次,在my_goods的this.goods 只是 某一个商品的信息
1、当用户点击 radio 组件,希望修改当前商品的勾选状态,此时用户可以为 my-goods 组件绑定 @radio-change 事件,从而获取当前商品的 goods_id 和 goods_state

<!-- 商品列表区域 -->
<block v-for="(goods, i) in cart" :key="i"><!-- 在 radioChangeHandler 事件处理函数中,通过事件对象 e,得到商品的 goods_id 和 goods_state --><my-goods :goods="goods" :show-radio="true" @radio-change="radioChangeHandler"></my-goods>
</block>
methods: {// 商品的勾选状态发生了变化radioChangeHandler(e) {console.log(e) // 输出得到的数据 -> {goods_id: 395, goods_state: false}}
}

2、在 my-goods.vue 组件中,为 radio 组件绑定 @click 事件处理函数如下

<!-- 商品左侧图片区域 -->
<view class="goods-item-left"><radio :checked="goods.goods_state" color="#C00000" v-if="showRadio" @click="radioClickHandler"></radio><image :src="goods.goods_small_logo || defaultPic" class="goods-pic"></image>
</view>

3、在 my-goods.vue 组件的 methods 节点中,定义 radioClickHandler 事件处理函数:

methods: {// radio 组件的点击事件处理函数radioClickHandler() {// 通过 this.$emit() 触发外界通过 @ 绑定的 radio-change 事件,// 同时把商品的 Id 和 勾选状态 作为参数传递给 radio-change 事件处理函数this.$emit('radio-change', {// 商品的 Idgoods_id: this.goods.goods_id,// 商品最新的勾选状态goods_state: !this.goods.goods_state})}
}

9.9 封装 点击事件

9.10 修改购物车的商品的勾选状态

1、在 store/cart.js 模块中,声明如下的 mutations 方法,用来修改对应商品的勾选状态

// 更新购物车中商品的勾选状态
updateGoodsState(state, goods) {// 根据 goods_id 查询购物车中对应商品的信息对象const findResult = state.cart.find(x => x.goods_id === goods.goods_id)// 有对应的商品信息对象if (findResult) {// 更新对应商品的勾选状态findResult.goods_state = goods.goods_state// 持久化存储到本地this.commit('m_cart/saveToStorage')}
}

2、在 cart.vue 页面中,导入 mapMutations 这个辅助函数,从而将需要的 mutations 方法映射到当前页面中使用

import badgeMix from '@/mixins/tabbar-badge.js'
import { mapState, mapMutations } from 'vuex'export default {mixins: [badgeMix],computed: {...mapState('m_cart', ['cart']),},data() {return {}},methods: {...mapMutations('m_cart', ['updateGoodsState']),// 商品的勾选状态发生了变化radioChangeHandler(e) {this.updateGoodsState(e)},},
}

9.11 为 my-goods 封装 numberbox

用 uni-ui 的 NumberBox 组件 NumberBox

1、基本结构

<view class="goods-info-box"><!-- 商品价格 --><view class="goods-price">¥{{goods.goods_price | tofixed}}</view><!-- 商品数量 --><uni-number-box :min="1"></uni-number-box>
</view>

2、美化结构

.goods-item-right {display: flex;flex: 1;flex-direction: column;justify-content: space-between;.goods-name {font-size: 13px;}.goods-info-box {display: flex;align-items: center;justify-content: space-between;}.goods-price {font-size: 16px;color: #c00000;}
}

3、动态绑定 numberBox 的值

<view class="goods-info-box"><!-- 商品价格 --><view class="goods-price">¥{{goods.goods_price | tofixed}}</view><!-- 商品数量 --><uni-number-box :min="1" :value="goods.goods_count"></uni-number-box>
</view>

9.12 通过 props 属性 实现控制 NumberBox的显示与隐藏

4、在 props 新增属性

    // 是否展示价格右侧的 NumberBox 组件showNum: {type: Boolean,default: false,},

5、用 v-if 控制 numberBox 的显示与隐藏
6、在 cart.vue 页面中的商品列表区域,指定 :show-num=“true” 属性,从而显示 NumberBox 组件

9.13 为 my-goods 组件封装 num-change 事件 思路

9.14 真正的实现

1、my-goods.vue 组件中,给 uni-number-box 组件绑定 @change 事件

<view class="goods-info-box"><!-- 商品价格 --><view class="goods-price">¥{{goods.goods_price | tofixed}}</view><!-- 商品数量 --><uni-number-box :min="1" :value="goods.goods_count" @change="numChangeHandler"></uni-number-box>
</view>

2、绑定事件

  // NumberBox 组件的 change 事件处理函数numChangeHandler(val) {// 通过 this.$emit() 触发外界通过 @ 绑定的 num-change 事件this.$emit('num-change', {// 商品的 Idgoods_id: this.goods.goods_id,// 商品的最新数量goods_count: +val})}

3、父组件 监听事件

<!-- 商品列表区域 -->
<block v-for="(goods, i) in cart" :key="i"><my-goods :goods="goods" :show-radio="true" :show-num="true" @radio-change="radioChangeHandler" @num-change="numberChangeHandler"></my-goods>
</block>

4、处理 父组件的 监听事件

// 商品的数量发生了变化
numberChangeHandler(e) {console.log(e)
}

9.15 解决 numberBox 数据不合法的问题

只让他输入 数字,输入非法的强制改成1

1、打开项目根目录中 components/uni-number-box/uni-number-box.vue 组件,修改 methods 节点中的 _onBlur 函数如下:

_onBlur(event) {// 官方的代码没有进行数值转换,用户输入的 value 值可能是非法字符:// let value = event.detail.value;// 将用户输入的内容转化为整数let value = parseInt(event.detail.value);if (!value) {// 如果转化之后的结果为 NaN,则给定默认值为 1this.inputValue = 1;return;}// 省略其它代码...
}

2、修改完毕之后,用户输入小数会被转化为整数,用户输入非法字符会被替换为默认值1

9.16 完善 numberBox 的侦听器

当我们输入 非法数字后,我们的 监听器 就会 立即执行,非法的数据在执行 就没有 意义 ,我们应该屏蔽掉

问题说明:在用户每次输入内容之后,都会触发 inputValue 侦听器,从而调用 this.$emit(“change”, newVal) 方法。这种做法可能会把不合法的内容传递出去!

1、打开项目根目录中 components/uni-number-box/uni-number-box.vue 组件,修改 watch 节点中的 inputValue 侦听器如下

inputValue(newVal, oldVal) {// 官方提供的 if 判断条件,在用户每次输入内容时,都会调用 this.$emit("change", newVal)// if (+newVal !== +oldVal) {// 新旧内容不同 && 新值内容合法 && 新值中不包含小数点if (+newVal !== +oldVal && Number(newVal) && String(newVal).indexOf('.') === -1) {this.$emit("change", newVal);}
}

2、修改完毕之后,NumberBox 组件只会把合法的、且不包含小数点的新值传递出去

9.17 修改 购物车中商品的数量

1、在 store/cart.js 模块中,声明如下的 mutations 方法,用来修改对应商品的数量

// 更新购物车中商品的数量
updateGoodsCount(state, goods) {// 根据 goods_id 查询购物车中对应商品的信息对象const findResult = state.cart.find(x => x.goods_id === goods.goods_id)if(findResult) {// 更新对应商品的数量findResult.goods_count = goods.goods_count// 持久化存储到本地this.commit('m_cart/saveToStorage')}
}

2、在 cart.vue 页面中,通过 mapMutations 这个辅助函数,将需要的 mutations 方法映射到当前页面中使用

import badgeMix from '@/mixins/tabbar-badge.js'
import { mapState, mapMutations } from 'vuex'export default {mixins: [badgeMix],computed: {...mapState('m_cart', ['cart']),},data() {return {}},methods: {...mapMutations('m_cart', ['updateGoodsState', 'updateGoodsCount']),// 商品的勾选状态发生了变化radioChangeHandler(e) {this.updateGoodsState(e)},// 商品的数量发生了变化numberChangeHandler(e) {this.updateGoodsCount(e)},},
}

9.18 滑动删除

uni-ui的uni-swiper-action
改善 cart 的购物车列表代码

     <!-- 商品列表区域 --><!-- uni-swipe-action 是最外层包裹性质的容器 --><uni-swipe-action><block v-for="(goods, i) in cart" :key="i"><!-- uni-swipe-action-item 可以为其子节点提供滑动操作的效果。需要通过 options 属性来指定操作按钮的配置信息 --><uni-swipe-action-item :right-options="options" @click="swipeActionClickHandler(goods)"><my-goods :goods="goods" :showRadio="true" @radio-change="radioChangeHandler" :showNum="true"@num-change="numberChangeHandler"></my-goods></uni-swipe-action-item></block></uni-swipe-action>data() {return {options: [{text: '删除', // 显示的文本内容style: {backgroundColor: '#C00000' // 按钮的背景颜色}}]}
}

改善 my-goods 的样式代码

.goods-item {// 让 goods-item 项占满整个屏幕的宽度width: 750rpx;// 设置盒模型为 border-boxbox-sizing: border-box;display: flex;padding: 10px 5px;border-bottom: 1px solid #f0f0f0;
}

9.19 实现滑动删除的效果

1、在 store/cart.js 模块的 mutations 节点中声明如下的方法,从而根据商品的 Id 从购物车中移除对应的商品

// 根据 Id 从购物车中删除对应的商品信息
removeGoodsById(state, goods_id) {// 调用数组的 filter 方法进行过滤state.cart = state.cart.filter(x => x.goods_id !== goods_id)// 持久化存储到本地this.commit('m_cart/saveToStorage')
}

2、在 cart.vue 页面中,使用 mapMutations 辅助函数,把需要的方法映射到当前页面中使用

methods: {...mapMutations('m_cart', ['updateGoodsState', 'updateGoodsCount', 'removeGoodsById']),// 商品的勾选状态发生了变化radioChangeHandler(e) {this.updateGoodsState(e)},// 商品的数量发生了变化numberChangeHandler(e) {this.updateGoodsCount(e)},// 点击了滑动操作按钮swipeActionClickHandler(goods) {this.removeGoodsById(goods.goods_id)}
}

10、收货地址功能实现

10.1 创建收货地址自定义组件

1、输入组件名字 my-address
2、使用 scss 模板,创建同名目录

10.2 收获地址基本UI的结构

<template><view><!-- 选择收货地址的盒子 --><view class="address-choose-box"><button type="primary" size="mini" class="btnChooseAddress">请选择收货地址+</button></view><!-- 底部的边框线 --><image src="/static/cart_border@2x.png" class="address-border"></image></view>
</template><script>export default {name: "my-address",data() {return {};}}
</script><style lang="scss">// 底部边框线的样式.address-border {display: block;width: 100%;height: 5px;}// 选择收货地址的盒子.address-choose-box {height: 90px;display: flex;align-items: center;justify-content: center;}// 渲染收货信息的盒子.address-info-box {font-size: 12px;height: 90px;display: flex;flex-direction: column;justify-content: center;padding: 0 5px;// 第一行.row1 {display: flex;justify-content: space-between;.row1-right {display: flex;align-items: center;.phone {margin-right: 5px;}}}// 第二行.row2 {display: flex;align-items: center;margin-top: 10px;.row2-left {white-space: nowrap;}}}
</style>

l0.3 渲染收货地址组件的UI结构

     <!-- 渲染收货信息的盒子 --><view class="address-info-box"><view class="row1"><view class="row1-left"><view class="username">收货人:<text>escook</text></view></view><view class="row1-right"><view class="phone">电话:<text>138XXXX5555</text></view><uni-icons type="arrowright" size="16"></uni-icons></view></view><view class="row2"><view class="row2-left">收货地址:</view><view class="row2-right">河北省邯郸市肥乡区xxx 河北省邯郸市肥乡区xxx 河北省邯郸市肥乡区xxx 河北省邯郸市肥乡区xxx </view></view></view>

10.4 实现收货地址区域的按需展示

有收货地址就不需要 显示 添加收货地址

1、在 data 中定义收货地址的信息对象
address:{}
2、使用 v-if 和 v-else 按需展示

<!-- 选择收货地址的盒子 -->
<view class="address-choose-box" v-if="JSON.stringify(address) === '{}'"><button type="primary" size="mini" class="btnChooseAddress">请选择收货地址+</button>
</view><!-- 渲染收货信息的盒子 -->
<view class="address-info-box" v-else><!-- 省略其它代码 -->
</view>

10.5 实现选择收货地址的功能

1、点击按钮绑定点击事件

2、事件处理函数

         // 选择收货地址async chooseAddress() {// 1. 调用小程序提供的 chooseAddress() 方法,即可使用选择收货地址的功能//    返回值是一个数组:第 1 项为错误对象;第 2 项为成功之后的收货地址对象// 如果选择了收货地址,返回的是一个数组,第一项是 null,第二项是数据对象const [err, succ] = await uni.chooseAddress().catch(err => err)// 2. 用户成功的选择了收货地址if (err === null && succ.errMsg === 'chooseAddress:ok') {// 为 data 里面的收货地址对象赋值this.address = succ}}

10.6 渲染收货人地址的信息

computed: {// 收货详细地址的计算属性addstr() {if (!this.address.provinceName) return ''// 拼接 省,市,区,详细地址 的字符串并返回给用户return this.address.provinceName + this.address.cityName + this.address.countyName + this.address.detailInfo}
}
<!-- 渲染收货信息的盒子 -->
<view class="address-info-box" v-else><view class="row1"><view class="row1-left"><view class="username">收货人:<text>{{address.userName}}</text></view></view><view class="row1-right"><view class="phone">电话:<text>{{address.telNumber}}</text></view><uni-icons type="arrowright" size="16"></uni-icons></view></view><view class="row2"><view class="row2-left">收货地址:</view><view class="row2-right">{{addstr}}</view></view>
</view>

10.7 在vuex中定义 m_user.js 模块

定义 引入

10.8 将address 存储到 vuex 中

1、改造 vue 组件的代码

// 1. 按需导入 mapState 和 mapMutations 这两个辅助函数
import { mapState, mapMutations } from 'vuex'export default {data() {return {// 2.1 注释掉下面的 address 对象,使用 2.2 中的代码替代之// address: {}}},methods: {// 3.1 把 m_user 模块中的 updateAddress 函数映射到当前组件...mapMutations('m_user', ['updateAddress']),// 选择收货地址async chooseAddress() {const [err, succ] = await uni.chooseAddress().catch((err) => err)// 用户成功的选择了收货地址if (err === null && succ.errMsg === 'chooseAddress:ok') {// 3.2 把下面这行代码注释掉,使用 3.3 中的代码替代之// this.address = succ// 3.3 调用 Store 中提供的 updateAddress 方法,将 address 保存到 Store 里面this.updateAddress(succ)}},},computed: {// 2.2 把 m_user 模块中的 address 对象映射当前组件中使用,代替 data 中 address 对象...mapState('m_user', ['address']),// 收货详细地址的计算属性addstr() {if (!this.address.provinceName) return ''// 拼接 省,市,区,详细地址 的字符串并返回给用户return this.address.provinceName + this.address.cityName + this.address.countyName + this.address.detailInfo},},
}

10.9 将vuex的 address 永久存储到本地

export default {// 开启命名空间namespaced: true,// state 数据state: () => ({// 3. 读取本地的收货地址数据,初始化 address 对象address: JSON.parse(uni.getStorageSync('address') || '{}'),}),// 方法mutations: {// 更新收货地址updateAddress(state, address) {state.address = address// 2. 通过 this.commit() 方法,调用 m_user 模块下的 saveAddressToStorage 方法将 address 对象持久化存储到本地this.commit('m_user/saveAddressToStorage')},// 1. 定义将 address 持久化存储到本地 mutations 方法saveAddressToStorage(state) {uni.setStorageSync('address', JSON.stringify(state.address))},},// 数据包装器getters: {},
}

10.10 将 addstr 抽离为 getters

// 数据包装器
getters: {// 收货详细地址的计算属性addstr(state) {if (!state.address.provinceName) return ''// 拼接 省,市,区,详细地址 的字符串并返回给用户return state.address.provinceName + state.address.cityName + state.address.countyName + state.address.detailInfo}
}
// 按需导入 mapGetters 辅助函数
import { mapState, mapMutations, mapGetters } from 'vuex'export default {// 省略其它代码computed: {...mapState('m_user', ['address']),// 将 m_user 模块中的 addstr 映射到当前组件中使用...mapGetters('m_user', ['addstr']),},
}

10.11 重新选择收货地址

给 渲染收获信息的盒子,绑定 chooseAdress 事件即可

10.12 取消授权的问题

当第一次加载的时候,会先 获取收货地址的信息,如果用户取消,则获取不到

10.13 判断用户是否授权

10.14 提示用户重新授权

// 选择收货地址
async chooseAddress() {// 1. 调用小程序提供的 chooseAddress() 方法,即可使用选择收货地址的功能//    返回值是一个数组:第1项为错误对象;第2项为成功之后的收货地址对象const [err, succ] = await uni.chooseAddress().catch(err => err)// 2. 用户成功的选择了收货地址if (succ && succ.errMsg === 'chooseAddress:ok') {// 更新 vuex 中的收货地址this.updateAddress(succ)}// 3. 用户没有授权if (err && err.errMsg === 'chooseAddress:fail auth deny') {this.reAuth() // 调用 this.reAuth() 方法,向用户重新发起授权申请}
}// 调用此方法,重新发起收货地址的授权
async reAuth() {// 3.1 提示用户对地址进行授权const [err2, confirmResult] = await uni.showModal({content: '检测到您没打开地址权限,是否去设置打开?',confirmText: "确认",cancelText: "取消",})// 3.2 如果弹框异常,则直接退出if (err2) return// 3.3 如果用户点击了 “取消” 按钮,则提示用户 “您取消了地址授权!”if (confirmResult.cancel) return uni.$showMsg('您取消了地址授权!')// 3.4 如果用户点击了 “确认” 按钮,则调用 uni.openSetting() 方法进入授权页面,让用户重新进行授权if (confirmResult.confirm) return uni.openSetting({// 3.4.1 授权结束,需要对授权的结果做进一步判断success: (settingResult) => {// 3.4.2 地址授权的值等于 true,提示用户 “授权成功”if (settingResult.authSetting['scope.address']) return uni.$showMsg('授权成功!请选择地址')// 3.4.3 地址授权的值等于 false,提示用户 “您取消了地址授权”if (!settingResult.authSetting['scope.address']) return uni.$showMsg('您取消了地址授权!')}})
}

11、结算

11.1 封装为独立的组件

1、创建组件
2、使用 scss 的组件
3、创建同名目录
my-settle

<template><view class="my-settle-container">结算</view>
</template><script>export default {name: "my-settle",data() {return {};}}
</script><style lang="scss">.my-settle-container {/* 底部固定定位 */position: fixed;bottom: 0;left: 0;/* 设置宽高和背景色 */width: 100%;height: 50px;background-color: cyan;}
</style>

给cart 根组件 加一个 cart-container 类,加上 padding-bottom:50px

结算区域的 ui 结构

<!-- 最外层的容器 -->
<view class="my-settle-container"><!-- 全选区域 --><label class="radio"><radio color="#C00000" :checked="true" /><text>全选</text></label><!-- 合计区域 --><view class="amount-box">合计:<text class="amount">¥1234.00</text></view><!-- 结算按钮 --><view class="btn-settle">结算(0)</view>
</view>
.my-settle-container {position: fixed;bottom: 0;left: 0;width: 100%;height: 50px;// 将背景色从 cyan 改为 whitebackground-color: white;display: flex;justify-content: space-between;align-items: center;padding-left: 5px;font-size: 14px;.radio {display: flex;align-items: center;}.amount {color: #c00000;}.btn-settle {height: 50px;min-width: 100px;background-color: #c00000;color: white;line-height: 50px;text-align: center;padding: 0 10px;}
}

11.2

11.3 渲染已勾选商品的总数量

1、在 store/cart.js 模块中,定义一个名称为 checkedCount 的 getters,用来统计已勾选商品的总数量

// 勾选的商品的总数量
checkedCount(state) {// 先使用 filter 方法,从购物车中过滤器已勾选的商品// 再使用 reduce 方法,将已勾选的商品总数量进行累加// reduce() 的返回值就是已勾选的商品的总数量return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count, 0)
}

2、在 my-settle 组件中,通过 mapGetters 辅助函数,将需要的 getters 映射到当前组件中使用

import { mapGetters } from 'vuex'export default {computed: {...mapGetters('m_cart', ['checkedCount']),},data() {return {}},
}
<!-- 结算按钮 -->
<view class="btn-settle">结算({{checkedCount}})</view>

10.4 动态渲染全选的按钮

# total 是 选择的商品的总数量,checkedCOUNT 是选中的数量
import { mapGetters } from 'vuex'export default {computed: {// 1. 将 total 映射到当前组件中...mapGetters('m_cart', ['checkedCount', 'total']),// 2. 是否全选isFullCheck() {return this.total === this.checkedCount},},data() {return {}},
}<!-- 全选区域 -->
<label class="radio"><radio color="#C00000" :checked="isFullCheck" /><text>全选</text>
</label>

10.5 改造

total(state){return state.cart.reduce((total,item)=> total += item.goods_count,0)
}

10.6 实现商品的全选与反选

1、在 store/cart.js 模块中,定义一个叫做 updateAllGoodsState 的 mutations 方法,用来修改所有商品的勾选状态

// 更新所有商品的勾选状态
updateAllGoodsState(state, newState) {// 循环更新购物车中每件商品的勾选状态state.cart.forEach(x => x.goods_state = newState)// 持久化存储到本地this.commit('m_cart/saveToStorage')
}

2、在 my-settle 组件中,通过 mapMutations 辅助函数,将需要的 mutations 方法映射到当前组件中使用

// 1. 按需导入 mapMutations 辅助函数
import { mapGetters, mapMutations } from 'vuex'export default {// 省略其它代码methods: {// 2. 使用 mapMutations 辅助函数,把 m_cart 模块提供的 updateAllGoodsState 方法映射到当前组件中使用...mapMutations('m_cart', ['updateAllGoodsState']),},
}

3、为 UI 中的 label 组件绑定 click 事件处理函数:

<!-- 全选区域 -->
<label class="radio" @click="changeAllState"><radio color="#C00000" :checked="isFullCheck" /><text>全选</text>
</label>

4、在 my-settle 组件的 methods 节点中,声明 changeAllState 事件处理函数

  // label 的点击事件处理函数changeAllState() {// 修改购物车中所有商品的选中状态// !this.isFullCheck 表示:当前全选按钮的状态取反之后,就是最新的勾选状态this.updateAllGoodsState(!this.isFullCheck)}

10.7 动态已勾选商品的价格

1、在 store/cart.js 模块中,定义一个叫做 checkedGoodsAmount 的 getters,用来统计已勾选商品的总价格

// 已勾选的商品的总价
checkedGoodsAmount(state) {// 先使用 filter 方法,从购物车中过滤器已勾选的商品// 再使用 reduce 方法,将已勾选的商品数量 * 单价之后,进行累加// reduce() 的返回值就是已勾选的商品的总价// 最后调用 toFixed(2) 方法,保留两位小数return state.cart.filter(x => x.goods_state).reduce((total, item) => total += item.goods_count * item.goods_price, 0).toFixed(2)
}

2、

...mapGetters('m_cart', ['total', 'checkedCount', 'checkedGoodsAmount'])

3、

<!-- 合计区域 -->
<view class="amount-box">合计:<text class="amount">¥{{checkedGoodsAmount}}</text>
</view>

10.8 动态计算购物车的徽标志

当我们在购物车页面 增加商品数量的时候,barbar的购物车 徽标值,并不会改变

改造 mixins/tabbar-badge.js 中的代码,使用 watch 侦听器,监听 total 总数量的变化,从而动态为 tabBar 的徽标赋值

import { mapGetters } from 'vuex'// 导出一个 mixin 对象
export default {computed: {...mapGetters('m_cart', ['total']),},watch: {// 监听 total 值的变化total() {// 调用 methods 中的 setBadge 方法,重新为 tabBar 的数字徽章赋值this.setBadge()},},onShow() {// 在页面刚展示的时候,设置数字徽标this.setBadge()},methods: {setBadge() {// 调用 uni.setTabBarBadge() 方法,为购物车设置右上角的徽标uni.setTabBarBadge({index: 2,text: this.total + '', // 注意:text 的值必须是字符串,不能是数字})},},
}

10.9 购物车为空的时候

改造 cart。vue

<template><view class="cart-container" v-if="cart.length !== 0"><!-- 使用自定义的 address 组件 --><!-- 购物车商品列表的标题区域 --><!-- 商品列表区域 --><!-- 结算区域 --></view><!-- 空白购物车区域 --><view class="empty-cart" v-else><image src="/static/cart_empty@2x.png" class="empty-img"></image><text class="tip-text">空空如也~</text></view>
</template>
.empty-cart {display: flex;flex-direction: column;align-items: center;padding-top: 150px;.empty-img {width: 90px;height: 90px;}.tip-text {font-size: 12px;color: gray;margin-top: 15px;}
}

12、登录功能

12.1 创建分支

git checkout -b settle

12.2 点击 结算 进行判断

用户点击了结算按钮之后,需要先后判断是否勾选了要结算的商品、是否选择了收货地址、是否登录。

1、绑定事件 my-settle

<!-- 结算按钮 -->
<view class="btn-settle" @click="settlement">结算({{checkedCount}})</view>

2、事件处理

// 点击了结算按钮
settlement() {// 1. 先判断是否勾选了要结算的商品if (!this.checkedCount) return uni.$showMsg('请选择要结算的商品!')// 2. 再判断用户是否选择了收货地址if (!this.addstr) return uni.$showMsg('请选择收货地址!')// 3. 最后判断用户是否登录了if (!this.token) return uni.$showMsg('请先登录!')
}

3、在 my-settle 组件中,使用 mapGetters 辅助函数,从 m_user 模块中将 addstr 映射到当前组件中使用

export default {computed: {...mapGetters('m_cart', ['total', 'checkedCount', 'checkedGoodsAmount']),// addstr 是详细的收货地址...mapGetters('m_user', ['addstr']),isFullCheck() {return this.total === this.checkedCount},},
}

4、在 store/user.js 模块的 state 节点中,声明 token 字符串
5、导入

// 按需从 vuex 中导入 mapState 辅助函数
import { mapGetters, mapMutations, mapState } from 'vuex'export default {computed: {...mapGetters('m_cart', ['total', 'checkedCount', 'checkedGoodsAmount']),...mapGetters('m_user', ['addstr']),// token 是用户登录成功之后的 token 字符串...mapState('m_user', ['token']),isFullCheck() {return this.total === this.checkedCount},},
}

12.3 添加登录页面编译模式

12.4 新建组件

my-login 新建登陆组件
my-userinfo 登录信息
在 my.vue 中 导入 这个 token

  <view><!-- 用户未登录时,显示登录组件 --><my-login v-if="!token"></my-login><!-- 用户登录后,显示用户信息组件 --><my-userinfo v-else></my-userinfo></view>

12.5 登陆组件的基本结构

<template><view><view class="login-container"><!-- 提示登录的图标 --><uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons><!-- 登录按钮 --><button type="primary" class="btn-login">一键登录</button><!-- 登录提示 --><view class="tips-text">登录后尽享更多权益</view></view></view>
</template><script>export default {name: "my-login",data() {return {};}}
</script><style lang="scss">.login-container {// 登录盒子的样式height: 750rpx;display: flex;flex-direction: column;align-items: center;justify-content: center;background-color: #f8f8f8;position: relative;overflow: hidden;// 绘制登录盒子底部的半椭圆造型&::after {content: ' ';display: block;position: absolute;width: 100%;height: 40px;left: 0;bottom: 0;background-color: white;border-radius: 100%;transform: translateY(50%);}// 登录按钮的样式.btn-login {width: 90%;border-radius: 100px;margin: 15px 0;background-color: #c00000;}// 按钮下方提示消息的样式.tips-text {font-size: 12px;color: gray;}}
</style>

12.6 样式

12.7 椭圆

12.8 登录功能实现思路

需要获取微信用户的头像、昵称等基本信息。
1、为登录的 button 按钮绑定 open-type=“getUserInfo” 属性,表示点击按钮时,希望获取用户的基本信息

<!-- 登录按钮 -->
<!-- 可以从 @getuserinfo 事件处理函数的形参中,获取到用户的基本信息 -->
<button type="primary" class="btn-login" open-type="getUserInfo" @getuserinfo="getUserInfo">一键登录</button>

2、

methods: {// 获取微信用户的基本信息getUserInfo(e) {// 判断是否获取用户信息成功if (e.detail.errMsg === 'getUserInfo:fail auth deny') return uni.$showMsg('您取消了登录授权!')// 获取用户信息成功, e.detail.userInfo 就是用户的基本信息console.log(e.detail.userInfo)}
}

12.9

12.10

12.11 将用户的基本信息存储在vuex 中

1、store/user.js

// 用户的基本信息userinfo: JSON.parse(uni.getStorageSync('userinfo') || '{}')

2、在 store/user.js 模块的 mutations 节点中,声明如下的两个方法

// 方法
mutations: {// 省略其它代码...// 更新用户的基本信息updateUserInfo(state, userinfo) {state.userinfo = userinfo// 通过 this.commit() 方法,调用 m_user 模块下的 saveUserInfoToStorage 方法,将 userinfo 对象持久化存储到本地this.commit('m_user/saveUserInfoToStorage')},// 将 userinfo 持久化存储到本地saveUserInfoToStorage(state) {uni.setStorageSync('userinfo', JSON.stringify(state.userinfo))}
}

3、使用 mapMutations 辅助函数,将需要的方法映射到 my-login 组件中使用

// 1. 按需导入 mapMutations 辅助函数
import { mapMutations } from 'vuex'export default {data() {return {}},methods: {// 2. 调用 mapMutations 辅助方法,把 m_user 模块中的 updateUserInfo 映射到当前组件中使用...mapMutations('m_user', ['updateUserInfo']),// 获取微信用户的基本信息getUserInfo(e) {// 判断是否获取用户信息成功if (e.detail.errMsg === 'getUserInfo:fail auth deny') return uni.$showMsg('您取消了登录授权!')// 获取用户信息成功, e.detail.userInfo 就是用户的基本信息// console.log(e.detail.userInfo)// 3. 将用户的基本信息存储到 vuex 中this.updateUserInfo(e.detail.userInfo)},},
}

将 token 存储到 vuex 中

1、在 store/user.js 模块的 mutations 节点中,声明如下的两个方法

mutations: {// 省略其它代码...// 更新 token 字符串updateToken(state, token) {state.token = token// 通过 this.commit() 方法,调用 m_user 模块下的 saveTokenToStorage 方法,将 token 字符串持久化存储到本地this.commit('m_user/saveTokenToStorage')},// 将 token 字符串持久化存储到本地saveTokenToStorage(state) {uni.setStorageSync('token', state.token)}
}

2、修改 store/user.js 的 token

  token: uni.getStorageSync('token') || '',

3、在登录成功后调用

13、用户信息组件

13.1 用户点击结算

需求描述:在购物车页面,当用户点击 “结算” 按钮时,如果用户没有登录,则 3 秒后自动跳转到登录页面
1、声明一个 倒计时提示消息方法
在 my-settle 组件的 methods 节点中,声明一个叫做 showTips 的方法,专门用来展示倒计时的提示消息

// 展示倒计时的提示消息
showTips(n) {// 调用 uni.showToast() 方法,展示提示消息uni.showToast({// 不展示任何图标icon: 'none',// 提示的消息title: '请登录后再结算!' + n + ' 秒后自动跳转到登录页',// 为页面添加透明遮罩,防止点击穿透mask: true,// 1.5 秒后自动消失duration: 1500})
}

2、在 data 节点中声明倒计时的秒数
seconds:3
3、改造结算按钮的处理函数

// 点击了结算按钮
settlement() {// 1. 先判断是否勾选了要结算的商品if (!this.checkedCount) return uni.$showMsg('请选择要结算的商品!')// 2. 再判断用户是否选择了收货地址if (!this.addstr) return uni.$showMsg('请选择收货地址!')// 3. 最后判断用户是否登录了,如果没有登录,则调用 delayNavigate() 进行倒计时的导航跳转// if (!this.token) return uni.$showMsg('请先登录!')if (!this.token) return this.delayNavigate()
},

4、定义 delayNavigate 方法,初步实现倒计时的提示功能

// 延迟导航到 my 页面
delayNavigate() {// 1. 展示提示消息,此时 seconds 的值等于 3this.showTips(this.seconds)// 2. 创建定时器,每隔 1 秒执行一次setInterval(() => {// 2.1 先让秒数自减 1this.seconds--// 2.2 再根据最新的秒数,进行消息提示this.showTips(this.seconds)}, 1000)
},

5、在 data中 定义 定时器 // 定时器的 Id
timer: null
6、改造 delayNavigate

delayNavigate() {this.showTips(this.seconds)// 1. 将定时器的 Id 存储到 timer 中this.timer = setInterval(() => {this.seconds--// 2. 判断秒数是否 <= 0if (this.seconds <= 0) {// 2.1 清除定时器clearInterval(this.timer)// 2.2 跳转到 my 页面uni.switchTab({url: '/pages/my/my'})// 2.3 终止后续代码的运行(当秒数为 0 时,不再展示 toast 提示消息)return}this.showTips(this.seconds)}, 1000)
},

7、进一步改造 delayNavigate 方法,在执行此方法时,立即将 seconds 秒数重置为 3 即可

// 延迟导航到 my 页面
delayNavigate() {// 把 data 中的秒数重置成 3 秒this.seconds = 3this.showTips(this.seconds)this.timer = setInterval(() => {this.seconds--if (this.seconds <= 0) {clearInterval(this.timer)uni.switchTab({url: '/pages/my/my'})return}this.showTips(this.seconds)}, 1000)
}

登录成功之后返回 原来的页面

1、在 store/user.js 模块的 state 节点中,声明一个叫做 redirectInfo 的对象如下

  // 重定向的 object 对象 { openType, from }redirectInfo: null

2、在 store/user.js 模块的 mutations 节点中,声明一个叫做 updateRedirectInfo 的方法

mutations: {// 更新重定向的信息对象updateRedirectInfo(state, info) {state.redirectInfo = info}
}

3、在 my-settle 组件中,通过 mapMutations 辅助方法,把 m_user 模块中的 updateRedirectInfo 方法映射到当前页面中使用
4、改造 my-settle 组件 methods 节点中的 delayNavigate 方法,当成功跳转到 my 页面 之后,将重定向的信息对象存储到 vuex 中

// 延迟导航到 my 页面
delayNavigate() {// 把 data 中的秒数重置成 3 秒this.seconds = 3this.showTips(this.seconds)this.timer = setInterval(() => {this.seconds--if (this.seconds <= 0) {// 清除定时器clearInterval(this.timer)// 跳转到 my 页面uni.switchTab({url: '/pages/my/my',// 页面跳转成功之后的回调函数success: () => {// 调用 vuex 的 updateRedirectInfo 方法,把跳转信息存储到 Store 中this.updateRedirectInfo({// 跳转的方式openType: 'switchTab',// 从哪个页面跳转过去的from: '/pages/cart/cart'})}})return}this.showTips(this.seconds)}, 1000)
}

5、在 my-login 组件中,通过 mapState 和 mapMutations 辅助方法,将 vuex 中需要的数据和方法,映射到当前页面中使用
6、在 获取 token 的 最后

// 调用登录接口,换取永久的 token
async getToken(info) {// 省略其它代码...// 判断 vuex 中的 redirectInfo 是否为 null// 如果不为 null,则登录成功之后,需要重新导航到对应的页面this.navigateBack()
}

7、返回原来的页面

// 返回登录之前的页面
navigateBack() {// redirectInfo 不为 null,并且导航方式为 switchTabif (this.redirectInfo && this.redirectInfo.openType === 'switchTab') {// 调用小程序提供的 uni.switchTab() API 进行页面的导航uni.switchTab({// 要导航到的页面地址url: this.redirectInfo.from,// 导航成功之后,把 vuex 中的 redirectInfo 对象重置为 nullcomplete: () => {this.updateRedirectInfo(null)}})}
}

14 发布

14.1 了解 uni 项目 发布为小程序项目的基本流程

1、点击 发行 点击 小程序-微信
2、添写名称 和 appid
3、打包
4、打包完成后,会自动打开一个 微信开发者工具界面,此时点击工具栏上的 上传 按钮 ,点击确定
5、输入版本号,备注,点击上传
6、上传完成之后,会出现如下的提示消息,直接点击确定按钮即可
7、通过微信开发者工具上传的代码,默认处于版本管理的开发版本列表中,如图所示:
8、将 开发版本提交审核 -> 再将 审核通过的版本发布上线,即可实现小程序的发布和上线

uni-app 学习笔记 黑马优购商城相关推荐

  1. HBuilder X ——Uni app 学习笔记(一)

    HBuilder X --Uni app 学习笔记(一) 1.pages.json配置 *pages数组中第一项表示应用启动页,数组中其他项为项目中所有页面路径. enablePullDownRefr ...

  2. 小程序黑马优购商城项目讲解

    小程序优购商城项目讲解 在我们开始之前 我们需要配好该项目所需要的接口文档以及配好相应的页面,以免在开发过程中会出现遗漏的问题出现. 首先我们要知道优购是分为4部分的 分别为 首页/列表/购物车/我的 ...

  3. 黑马优购商城首页的实现

    文章目录 1.1效果图 1.2搜索框 1.2.1新建组件 1.2.2编写组件 1.2.3引用组件 1.2.4使用组件 1.2.5效果 1.3轮播图 1.3.1获取网络接口 1.3.1编写轮播图 1.4 ...

  4. uniapp微信小程序项目-优购商城

    原网页笔记文档: https://www.escook.cn/docs-uni-shop/ 1. 起步 #1.1 uni-app 简介 uni-app 是一个使用 Vue.js 开发所有前端应用的框架 ...

  5. 黑马优购_微信小程序

    黑马优购_微信小程序项目 介绍 2021年5月6日-2021年5月12日在校参加微信小程序培训,由黑马讲师授课,能够利用微信提供的组件和API实现轮播图.授权用户信息.上拉加载更多等功能,由于之前对u ...

  6. 小程序swiper怎么让内容撑开高度_[视频]微信小程序实战优购商城,涵盖你所学的技能点...

    很多友友都在找视频教程学习,IT技术教程分享网[http://www.mano100.cn]已经为你收集了各种各样的视频教程,不用再到处找视频教程学习了.无论是免费的,还是收费的,都在这里了.只要你注 ...

  7. 品优购商城——列表页

    效果图: 列表页文件 list.html <!DOCTYPE html> <html lang="en"> <head><meta cha ...

  8. 品优购商城——手机详情页(作业)

    效果图: 手机详情页文件 detail.html <!DOCTYPE html> <html lang="en"> <head><meta ...

  9. 优购商城项目 详细步骤流程

    优购商城项目 详细步骤流程 一.准备的工作 1.文档 写项目之前必须要有接口文档 准备工作接口文档是必不可少的 参考文档我们还可以参考 小程序的开发文档.阿里巴巴字体 iconfont .mdn- 2 ...

最新文章

  1. linux安装manjaro创建分区失败,如何安装Manjaro Linux [最强指南]? 看完就知道了
  2. 十大排序算法之选择排序
  3. 微机原理换行代码_设置段落样式的标记中,用来换行的标记是:
  4. 给i茅台APP提几个建议
  5. java百度结果的正则表达式_java正则表达式
  6. window.onload和$(function(){})的区别介绍
  7. javap 指令集 (转)
  8. Flask实现REST API之接收POST和GET请求
  9. 图书销售系统可行性分析报告
  10. 为你的企业建立竞争情报系统
  11. 服务器磁盘配置信息,服务器磁盘阵列配置
  12. 嵌入式工程师学习路线(软件类)
  13. 【Python】所有常用Python库和功能查询表
  14. ios 字符加密问题 字符串加密gyb字符返回空
  15. Math.h 正态分布 C语言,C++与正态分布(示例代码)
  16. Emlog资源网下载主题模板源码
  17. pyton入门 — 其他常用语法
  18. 抖音上热门精选的要求 视频怎么修改md5
  19. Delphi图像处理 -- 灰色浮雕
  20. java 线程锁Lock

热门文章

  1. 软通动力入职考试----全套
  2. word文档合并单元格在什么地方
  3. navicat中导出数据表结构为word格式
  4. Python玩转数据分析——双因素方差分析
  5. 从零开始搭建自己的网站二十一:网站IP/PV统计功能设计
  6. div css实现进度条
  7. 完美世界手游服务器维护时间表,完美世界手游开服时间表 新区开服时间总览[多图]...
  8. jupyterlab:Failed to load the jupyterlab-git server extension问题如何解决?
  9. 笨方法学python 习题32-33
  10. python 升级setuptools_python3.6升级及setuptools、pip安装