本文介紹了透過uniapp技術實現了一套梔子手作線上購物商城系統。包含首頁、分類、我的等常用功能入口。
一、功能演示
首頁:包含了商品介紹,領劵中心和商品列表區域。
商品分類:支援不同的商品分類和商品搜素。
商品詳情:包含了商品詳細的描述資訊,透出了分享、首頁、客服等入口。
我的:包含了賬戶的常見的個人操作資訊,知乎此領劵,線上客服,錢包管理等入口。
H5端線上體驗地址:https://wx.gaoredu.com/
微信小程式:可以直接搜尋“梔子手作”進入線上體驗。
二、開發流程
2.1 專案準備與搭建
1. 環境搭建
首先,確保你已經安裝了Node.js和HBuilderX,因為uniapp的專案可以透過HBuilderX來方便地建立和管理。安裝HBuilderX後,在官網(https://www.dcloud.io/hbuilderx.html)下載並安裝。
2. 建立uniapp專案
啟動HBuilderX,點選選單欄中的“檔案”→“新建”→“專案”,選擇“uni-app”型別,輸入專案名稱(如“huahuaMall”),選擇專案儲存路徑,點選“建立”按鈕。專案建立成功後,你會看到一個基本的專案結構,包括pages
、static
、components
等目錄。
2.2 首頁設計
這裡是梔子手作的小店的首頁設計:
1. 頁面佈局
首頁是商城的門戶,通常包含輪播圖、搜尋框、熱門商品列表等功能模組。
- 輪播圖:使用
<swiper>
和<swiper-item>
元件展示。 - 搜尋框:自定義一個搜尋元件,可以放置在
<view class="header">
中。 - 商品列表:使用
<view v-for="...">
迴圈遍歷商品資料,每個商品使用<view class="product-item">
展示。
2. 示例程式碼
<template>
<view class="container" :style="appThemeStyle">
<!-- 店鋪頁面元件 -->
<Page :items="items" />
<!-- 使用者隱私保護提示(僅微信小程式) -->
<!-- #ifdef MP-WEIXIN -->
<PrivacyPopup :hideTabBar="true" />
<!-- #endif -->
</view>
</template>
<script>
import { setCartTabBadge } from '@/core/app'
import * as Api from '@/api/page'
import Page from '@/components/page'
import PrivacyPopup from '@/components/privacy-popup'
const App = getApp()
export default {
components: {
Page,
PrivacyPopup
},
data() {
return {
// 頁面引數
options: {},
// 頁面屬性
page: {},
// 頁面元素
items: []
}
},
/**
* 生命週期函式--監聽頁面載入
*/
onLoad(options) {
// 當前頁面引數
this.options = options
// 載入頁面資料
this.getPageData()
},
/**
* 生命週期函式--監聽頁面顯示
*/
onShow() {
// 更新購物車角標
setCartTabBadge()
},
methods: {
/**
* 載入頁面資料
* @param {Object} callback
*/
getPageData(callback) {
const app = this
const pageId = app.options.pageId || 0
Api.detail(pageId)
.then(result => {
// 設定頁面資料
const { data: { pageData } } = result
app.page = pageData.page
app.items = pageData.items
// 設定頂部導航欄欄
app.setPageBar()
})
.finally(() => callback && callback())
},
/**
* 設定頂部導航欄
*/
setPageBar() {
const { page } = this
// 設定頁面標題
uni.setNavigationBarTitle({
title: page.params.title
})
// 設定navbar標題、顏色
uni.setNavigationBarColor({
frontColor: page.style.titleTextColor === 'white' ? '#ffffff' : '#000000',
backgroundColor: page.style.titleBackgroundColor
})
}
},
/**
* 下拉重新整理
*/
onPullDownRefresh() {
// 獲取首頁資料
this.getPageData(() => {
uni.stopPullDownRefresh()
})
},
/**
* 分享當前頁面
*/
onShareAppMessage() {
const app = this
const { page } = app
return {
title: page.params.shareTitle,
path: "/pages/index/index?" + app.$getShareUrlParams()
}
},
/**
* 分享到朋友圈
* 本介面為 Beta 版本,暫只在 Android 平臺支援,詳見分享到朋友圈 (Beta)
* https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share-timeline.html
*/
onShareTimeline() {
const app = this
const { page } = app
return {
title: page.params.shareTitle,
path: "/pages/index/index?" + app.$getShareUrlParams()
}
}
}
</script>
<style lang="scss" scoped>
.container {
background: #fff;
}
</style>
2.3 分類頁面設計
<template>
<view class="container">
<!-- 搜尋框 -->
<view class="search">
<search tips="搜尋商品" @event="$navTo('pages/search/index')" />
</view>
<!-- 一級分類 -->
<primary
v-if="setting.style == PageCategoryStyleEnum.ONE_LEVEL_BIG.value || setting.style == PageCategoryStyleEnum.ONE_LEVEL_SMALL.value"
:display="setting.style" :list="list" />
<!-- 二級分類 -->
<secondary v-if="setting.style == PageCategoryStyleEnum.TWO_LEVEL.value" :list="list" />
<!-- 分類+商品 -->
<commodity v-if="setting.style == PageCategoryStyleEnum.COMMODITY.value" ref="mescrollItem" :list="list" :setting="setting" />
</view>
</template>
<script>
import MescrollCompMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mixins/mescroll-comp'
import { setCartTabBadge } from '@/core/app'
import SettingKeyEnum from '@/common/enum/setting/Key'
import { PageCategoryStyleEnum } from '@/common/enum/store/page/category'
import SettingModel from '@/common/model/Setting'
import * as CategoryApi from '@/api/category'
import Search from '@/components/search'
import Primary from './components/primary'
import Secondary from './components/secondary'
import Commodity from './components/commodity'
// 最後一次重新整理時間
let lastRefreshTime;
export default {
components: {
Search,
Primary,
Secondary,
Commodity
},
mixins: [MescrollCompMixin],
data() {
return {
// 列舉類
PageCategoryStyleEnum,
// 分類列表
list: [],
// 分類别範本設定
setting: {},
// 正在載入中
isLoading: true
}
},
/**
* 生命週期函式--監聽頁面載入
*/
onLoad() {
// 載入頁面資料
this.onRefreshPage()
},
/**
* 生命週期函式--監聽頁面顯示
*/
onShow() {
// 每間隔5分鐘自動重新整理一次頁面資料
const curTime = new Date().getTime()
if ((curTime - lastRefreshTime) > 5 * 60 * 1000) {
this.onRefreshPage()
}
},
methods: {
// 重新整理頁面
onRefreshPage() {
// 記錄重新整理時間
lastRefreshTime = new Date().getTime()
// 獲取頁面資料
this.getPageData()
// 更新購物車角標
setCartTabBadge()
},
// 獲取頁面資料
getPageData() {
const app = this
app.isLoading = true
Promise.all([
// 獲取分類别範本設定
// 最佳化建議: 可以將此處的false改為true 啟用快取
SettingModel.data(false),
// 獲取分類列表
CategoryApi.list()
])
.then(result => {
// 初始化分類别範本設定
app.initSetting(result[0])
// 初始化分類列表資料
app.initCategory(result[1])
})
.finally(() => app.isLoading = false)
},
/**
* 初始化分類别範本設定
* @param {Object} result
*/
initSetting(setting) {
this.setting = setting[SettingKeyEnum.PAGE_CATEGORY_TEMPLATE.value]
},
/**
* 初始化分類列表資料
* @param {Object} result
*/
initCategory(result) {
this.list = result.data.list
},
},
/**
* 設定分享內容
*/
onShareAppMessage() {
const app = this
return {
title: _this.templet.shareTitle,
path: '/pages/category/index?' + app.$getShareUrlParams()
}
},
/**
* 分享到朋友圈
* 本介面為 Beta 版本,暫只在 Android 平臺支援,詳見分享到朋友圈 (Beta)
* https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share-timeline.html
*/
onShareTimeline() {
const app = this
return {
title: _this.templet.shareTitle,
path: '/pages/category/index?' + app.$getShareUrlParams()
}
}
}
</script>
<style>
page {
background: #fff;
}
</style>
<style lang="scss" scoped>
// 搜尋框
.search {
position: fixed;
top: var(--window-top);
left: var(--window-left);
right: var(--window-right);
z-index: 9;
}
</style>
2.4 商品詳情頁面設計
相關程式碼演示:
<template>
<view v-show="!isLoading" class="container" :style="appThemeStyle">
<!-- 商品圖片輪播 -->
<SlideImage v-if="!isLoading" :video="goods.video" :videoCover="goods.videoCover"
:images="goods.goods_images" />
<!-- 商品資訊 -->
<view v-if="!isLoading" class="goods-info m-top20">
<!-- 價格、銷量 -->
<view class="info-item info-item__top dis-flex flex-x-between flex-y-end">
<view class="block-left dis-flex flex-y-center">
<!-- 商品售價 -->
<text class="floor-price__samll">¥</text>
<text class="floor-price">{{ goods.goods_price_min }}</text>
<!-- 會員價標籤 -->
<view v-if="goods.is_user_grade" class="user-grade">
<text>會員價</text>
</view>
<!-- 劃線價 -->
<text v-if="goods.line_price_min > 0" class="original-price">¥{{ goods.line_price_min }}</text>
</view>
<view class="block-right dis-flex">
<!-- 銷量 -->
<view class="goods-sales">
<text>已售{{ goods.goods_sales }}件</text>
</view>
</view>
</view>
<!-- 標題、分享 -->
<view class="info-item info-item__name dis-flex flex-y-center">
<view class="goods-name flex-box">
<text class="twoline-hide">{{ goods.goods_name }}</text>
</view>
<view class="goods-share__line"></view>
<view class="goods-share">
<button class="share-btn dis-flex flex-dir-column" @click="onShowShareSheet()">
<text class="share__icon iconfont icon-fenxiang"></text>
<text class="f-24">分享</text>
</button>
</view>
</view>
<!-- 商品賣點 -->
<view v-if="goods.selling_point" class="info-item info-item_selling-point">
<text>{{ goods.selling_point }}</text>
</view>
</view>
<!-- 選擇商品規格 -->
<view v-if="goods.spec_type == 20" class="goods-choice m-top20 b-f" @click="onShowSkuPopup(1)">
<view class="spec-list">
<view class="flex-box">
<text class="col-8">選擇:</text>
<text class="spec-name" v-for="(item, index) in goods.specList"
:key="index">{{ item.spec_name }}</text>
</view>
<view class="f-26 col-9 t-r">
<text class="iconfont icon-arrow-right"></text>
</view>
</view>
</view>
<!-- 商品服務 -->
<Service v-if="!isLoading" :goods-id="goodsId" />
<!-- 商品SKU彈窗 -->
<SkuPopup v-if="!isLoading" v-model="showSkuPopup" :skuMode="skuMode" :goods="goods" @addCart="onAddCart" />
<!-- 商品評價 -->
<Comment v-if="!isLoading" :goods-id="goodsId" :limit="2" />
<!-- 商品描述 -->
<view v-if="!isLoading" class="goods-content m-top20">
<view class="item-title b-f">
<text>商品描述</text>
</view>
<view v-if="goods.content != ''" class="goods-content__detail b-f">
<mp-html :content="goods.content" />
</view>
</view>
<!-- 底部選項卡 -->
<view class="footer-fixed">
<view class="footer-container">
<!-- 導航圖示 -->
<view class="foo-item-fast">
<!-- 首頁 -->
<view class="fast-item fast-item--home" @click="onTargetHome">
<view class="fast-icon">
<text class="iconfont icon-shouye"></text>
</view>
<view class="fast-text">
<text>首頁</text>
</view>
</view>
<!-- 客服 -->
<customer-btn v-if="isShowCustomerBtn" :showCard="true" :cardTitle="goods.goods_name"
:cardImage="goods.goods_image">
<view class="fast-item">
<view class="fast-icon">
<text class="iconfont icon-kefu1"></text>
</view>
<view class="fast-text">
<text>客服</text>
</view>
</view>
</customer-btn>
<!-- 購物車 -->
<!-- <view class="fast-item fast-item--cart" @click="onTargetCart">
<view v-if="cartTotal > 0" class="fast-badge fast-badge--fixed">{{ cartTotal > 99 ? '99+' : cartTotal }}
</view>
<view class="fast-icon">
<text class="iconfont icon-gouwuche"></text>
</view>
<view class="fast-text">
<text>購物車</text>
</view>
</view> -->
</view>
<!-- 操作按鈕 -->
<view class="foo-item-btn">
<view class="btn-wrapper">
<!-- <view v-if="isEnableCart" class="btn-item btn-item-deputy" @click="onShowSkuPopup(2)">
<text>加入購物車</text>
</view> -->
<view class="btn-item btn-item-main" @click="onShowSkuPopup(3)">
<text>更多詳情</text>
</view>
</view>
</view>
</view>
</view>
<!-- 快捷導航 -->
<!-- <shortcut bottom="120rpx" /> -->
<!-- 分享選單 -->
<share-sheet v-model="showShareSheet" :shareTitle="goods.goods_name" :shareImageUrl="goods.goods_image" />
<!-- 二維碼掃碼 -->
<u-modal v-model="showQrModal" :title="溫馨提示">
<view class="qrcode">
<text>下單請長按二維碼➕微信</text>
<image src="../../static/qrcode.jpg" mode="widthFix" :show-menu-by-longpress="true"/>
</view>
</u-modal>
</view>
</template>
<script>
import {
getSceneData
} from '@/core/app'
import * as GoodsApi from '@/api/goods'
import * as CartApi from '@/api/cart'
import SettingModel from '@/common/model/Setting'
import {
GoodsTypeEnum
} from '@/common/enum/goods'
import ShareSheet from '@/components/share-sheet'
import CustomerBtn from '@/components/customer-btn'
import SlideImage from './components/SlideImage'
import SkuPopup from './components/SkuPopup'
import Comment from './components/Comment'
import Service from './components/Service'
export default {
components: {
ShareSheet,
CustomerBtn,
SlideImage,
SkuPopup,
Comment,
Service
},
data() {
return {
// 正在載入
isLoading: true,
// 當前商品ID
goodsId: null,
// 商品詳情
goods: {},
// 購物車總數量
cartTotal: 0,
// 顯示/隱藏SKU彈窗
showSkuPopup: false,
// 模式 1:都顯示 2:只顯示購物車 3:只顯示立即購買
skuMode: 1,
// 顯示/隱藏分享選單
showShareSheet: false,
// 是否支援加入購物車
isEnableCart: false,
// 是否顯示線上客服按鈕
isShowCustomerBtn: false,
// 是否展示QrModal
showQrModal: false,
}
},
/**
* 生命週期函式--監聽頁面載入
*/
async onLoad(options) {
// 記錄query引數
this.onRecordQuery(options)
// 載入頁面資料
this.onRefreshPage()
// 是否顯示線上客服按鈕
this.isShowCustomerBtn = await SettingModel.isShowCustomerBtn()
},
methods: {
// 記錄query引數
onRecordQuery(query) {
const scene = getSceneData(query)
this.goodsId = query.goodsId ? parseInt(query.goodsId) : parseInt(scene.gid)
},
// 重新整理頁面資料
onRefreshPage() {
const app = this
app.isLoading = true
Promise.all([app.getGoodsDetail(), app.getCartTotal()])
.finally(() => app.isLoading = false)
},
// 獲取商品資訊
getGoodsDetail() {
const app = this
return new Promise((resolve, reject) => {
GoodsApi.detail(app.goodsId)
.then(result => {
app.goods = result.data.detail
if (app.goods.goods_type == GoodsTypeEnum.PHYSICAL.value) {
app.isEnableCart = true
}
resolve(result)
})
.catch(reject)
})
},
// 獲取購物車總數量
getCartTotal() {
const app = this
return new Promise((resolve, reject) => {
CartApi.total()
.then(result => {
app.cartTotal = result.data.cartTotal
resolve(result)
})
.catch(reject)
})
},
// 更新購物車數量
onAddCart(total) {
this.cartTotal = total
},
/**
* 顯示/隱藏SKU彈窗
* @param {skuMode} 模式 1:都顯示 2:只顯示購物車 3:只顯示立即購買
*/
onShowSkuPopup(skuMode = 1) {
// 下單請聯絡客服
this.showQrModal = true;
// uni.showModal({
// title: '溫馨提示',
// content: '下單請聯絡客服或➕微信:zzsz68'
// });
// WARNING:如下臨時註釋
// const app = this
// if (app.isEnableCart) {
// app.skuMode = skuMode
// } else {
// app.skuMode = 3
// }
// app.showSkuPopup = !app.showSkuPopup
},
// 顯示隱藏分享選單
onShowShareSheet() {
this.showShareSheet = !this.showShareSheet
},
// 跳轉到首頁
onTargetHome(e) {
this.$navTo('pages/index/index')
},
// 跳轉到購物車頁
onTargetCart() {
this.$navTo('pages/cart/index')
},
},
/**
* 分享當前頁面
*/
onShareAppMessage() {
const app = this
// 構建頁面引數
const params = app.$getShareUrlParams({
goodsId: app.goodsId,
})
return {
title: app.goods.goods_name,
path: `/pages/goods/detail?${params}`
}
},
/**
* 分享到朋友圈
* 本介面為 Beta 版本,暫只在 Android 平臺支援,詳見分享到朋友圈 (Beta)
* https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/share-timeline.html
*/
onShareTimeline() {
const app = this
// 構建頁面引數
const params = app.$getShareUrlParams({
goodsId: app.goodsId,
})
return {
title: app.goods.goods_name,
path: `/pages/goods/detail?${params}`
}
}
}
</script>
<style>
page {
background: #fafafa;
}
</style>
<style lang="scss" scoped>
@import "./detail.scss";
</style>
2.4 我的頁面設計
<template> <view v-if="!isFirstload" class="container" :style="appThemeStyle"> <!-- 頁面頭部 --> <view class="main-header" :style="{ height: platform == 'H5' ? '260rpx' : '320rpx', paddingTop: platform == 'H5' ? '0' : '80rpx' }"> <image class="bg-image" src="/static/background/user-header2.png" mode="scaleToFill"></image> <!-- 使用者資訊 --> <view v-if="isLogin" class="user-info"> <view class="user-avatar" @click="handlePersonal()"> <avatar-image :url="userInfo.avatar_url" :width="100" /> </view> <view class="user-content"> <!-- 會員暱稱 --> <view class="nick-name oneline-hide" @click="handlePersonal()">{{ userInfo.nick_name }}</view> <!-- 會員等級 --> <view v-if="$checkModule('user-grade') && userInfo.grade_id > 0 && userInfo.grade" class="user-grade"> <view class="user-grade_icon"> <image class="image" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAMAAABEpIrGAAAA0lBMVEUAAAD/tjL/tzH/uDP/uC7/tjH/tzH/tzL/tTH+tTL+tjP/tDD/tTD+tzD/tjL/szD/uDH/tjL/tjL+tjD/tjT/szb/tzL/tTL+uTH+tjL/tjL/tjL/tTT/tjL/tjL+tjH/uTL/vDD/tjL/tjH/tzL9uS//tTL/nBr/sS7/tjH/ujL/szD/uTv+rzf/tzL+tzH+vDP+uzL+tjP+ry7+tDL9ki/7szf/sEX/tTL/tjL+tjL/tTH/tTT/tzH/tzL/tjP/sTX/uTP/wzX+rTn/vDX9vC8m8ckhAAAAOXRSTlMAlnAMB/vjxKWGMh0S6drMiVxPRkEY9PLy0ru0sKagmo5+dGtgVCMgBP716eXWyMGxqJGRe2o5KSmFNjaYAAABP0lEQVQ4y8XS13KDMBAF0AWDDe4t7r3ETu9lVxJgJ/n/X8rKAzHG5TE+Twz3zki7I/g/KXdghIbGJewrU4yzn08Ebgl6TuZzzuOC6W5es3HX6qsSz3NFShRU0MpucytDmOSpu3yULx3CA9RD1HjVedc0jSjqm6ZzhUjDsFDQhSp/OKj5GQvg0+ZCOixsbtDLAeTTOm/yGi8GyIphIVsgH737FEDV44LJa88IRKK/SetrwT9G/GUIr6vXjoy4GXn7+RboVXnghuSjaoGecwQxL2su3CwAKlO+QFoqxI4FMctHQhQd2OhxTu184jWUlI+rMTBTn1/IQcJHQ6GQdZ7pWiDaNdhTt330efISeiqYwQEzQpTlsURJLhzkEmpCPsERfeIUVyXr6MNuIyp5uziW6xURtt7hhGwzmMNJExfO4Bd9X0ZPqAxdNwAAAABJRU5ErkJggg=="> </image> </view> <view class="user-grade_name"> <text>{{ userInfo.grade.name }}</text> </view> </view> <!-- 會員無等級時顯示手機號 --> <view v-else class="mobile">{{ userInfo.mobile }}</view> </view> </view> <!-- 未登入 --> <view v-else class="user-info" @click="handleLogin"> <view class="user-avatar"> <avatar-image :width="100" /> </view> <view class="user-content"> <view class="nick-name">未登入</view> <view class="login-tips">點選登入賬號</view> </view> </view> </view> <!-- 繫結手機號 --> <!-- <view v-if="isLogin && !userInfo.mobile && setting[SettingKeyEnum.REGISTER.value].isManualBind" class="my-mobile" @click="handleBindMobile()"> <view class="info">點選繫結手機號,確保賬戶安全</view> <view class="btn-bind">去繫結</view> </view> --> <!-- 我的錢包 --> <view v-if="$checkModules(['market-recharge', 'market-points', 'market-coupon'])" class="my-asset"> <view class="asset-left flex-box dis-flex flex-x-around"> <view v-if="$checkModule('market-recharge')" class="asset-left-item" style="max-width: 200rpx;" @click="onTargetWallet"> <view class="item-value dis-flex flex-x-center"> <text class="oneline-hide">{{ isLogin ? assets.balance : '--' }}</text> </view> <view class="item-name dis-flex flex-x-center"> <text>賬戶餘額</text> </view> </view> <view v-if="$checkModule('market-points')" class="asset-left-item" @click="onTargetPoints"> <view class="item-value dis-flex flex-x-center"> <text class="oneline-hide">{{ isLogin ? assets.points : '--' }}</text> </view> <view class="item-name dis-flex flex-x-center"> <text>{{ setting[SettingKeyEnum.POINTS.value].points_name }}</text> </view> </view> <view v-if="$checkModule('market-coupon')" class="asset-left-item" @click="onTargetMyCoupon"> <view class="item-value dis-flex flex-x-center"> <text class="oneline-hide">{{ isLogin ? assets.coupon : '--' }}</text> </view> <view class="item-name dis-flex flex-x-center"> <text>優惠券</text> </view> </view> </view> <view v-if="$checkModule('market-recharge')" class="asset-right"> <view class="asset-right-item" @click="onTargetWallet"> <view class="item-icon dis-flex flex-x-center"> <text class="iconfont icon-qianbao"></text> </view> <view class="item-name dis-flex flex-x-center"> <text>我的錢包</text> </view> </view> </view> </view> <!-- 繫結手機號 (第2種樣式) --> <!-- <view class="my-mobile2" @click="handleBindMobile()"> <view class="info">點選繫結手機號,確保賬戶安全</view> <view class="btn-bind">去繫結</view> </view> --> <!-- 訂單操作 --> <!-- <view class="order-navbar"> <view class="order-navbar-item" v-for="(item, index) in orderNavbar" :key="index" @click="onTargetOrder(item)"> <view class="item-icon"> <text class="iconfont" :class="[`icon-${item.icon}`]"></text> </view> <view class="item-name">{{ item.name }}</view> <view class="item-badge" v-if="item.count && item.count > 0"> <text v-if="item.count <= 99" class="text">{{ item.count }}</text> <text v-else class="text">99+</text> </view> </view> </view> --> <!-- 我的服務 --> <view class="my-service"> <view class="service-title">我的服務</view> <view class="service-content clearfix"> <block v-for="(item, index) in service" :key="index"> <view v-if="item.type == 'link' && item.enabled" class="service-item" @click="handleService(item)"> <view class="item-icon"> <text class="iconfont" :class="[`icon-${item.icon}`]"></text> </view> <view class="item-name">{{ item.name }}</view> <view class="item-badge" v-if="item.count && item.count > 0"> <text v-if="item.count <= 99" class="text">{{ item.count }}</text> <text v-else class="text">99+</text> </view> </view> <!-- 線上客服 --> <view v-if="item.type == 'contact' && item.enabled" class="service-item"> <customer-btn> <view class="item-icon"> <text class="iconfont" :class="[`icon-${item.icon}`]"></text> </view> <view class="item-name">{{ item.name }}</view> </customer-btn> </view> </block> </view> </view> <!-- 退出登入 --> <view v-if="isLogin" class="my-logout"> <view class="logout-btn" @click="handleLogout()"> <text>退出登入</text> </view> </view> </view> </template> <script> import store from '@/store' import { inArray } from '@/utils/util' import AvatarImage from '@/components/avatar-image' import CustomerBtn from '@/components/customer-btn' import { setCartTabBadge } from '@/core/app' import SettingKeyEnum from '@/common/enum/setting/Key' import StoreModel from '@/common/model/Store' import SettingModel from '@/common/model/Setting' import * as UserApi from '@/api/user' import * as OrderApi from '@/api/order' import { checkLogin, filterModules } from '@/core/app' // 訂單操作 const orderNavbar = [ { id: 'all', name: '全部訂單', icon: 'qpdingdan' }, { id: 'payment', name: '待支付', icon: 'daifukuan', count: 0 }, { id: 'delivery', name: '待發貨', icon: 'daifahuo', count: 0 }, { id: 'received', name: '待收貨', icon: 'daishouhuo', count: 0 }, ] /** * 我的服務 * id: 標識; name: 標題名稱; icon: 圖示; type 型別(link和button); url: 跳轉的連結 */ const service = [ // { id: 'address', name: '收貨地址', icon: 'shouhuodizhi', type: 'link', url: 'pages/address/index' }, { id: 'coupon', name: '領券中心', icon: 'lingquan', type: 'link', url: 'pages/coupon/index', moduleKey: 'market-coupon' }, { id: 'myCoupon', name: '優惠券', icon: 'youhuiquan', type: 'link', url: 'pages/my-coupon/index', moduleKey: 'market-coupon' }, // { id: 'refund', name: '退換/售後', icon: 'shouhou', type: 'link', url: 'pages/refund/index', count: 0 }, { id: 'contact', name: '線上客服', icon: 'kefu', type: 'contact' }, { id: 'points', name: '我的積分', icon: 'jifen', type: 'link', url: 'pages/points/log', moduleKey: 'market-points' }, // { id: 'orderCenter', name: '訂單中心', icon: 'order-c', type: 'link', url: 'pages/order/center' }, // { id: 'help', name: '我的幫助', icon: 'bangzhu', type: 'link', url: 'pages/help/index', moduleKey: 'content-help' }, ] export default { components: { AvatarImage, CustomerBtn }, data() { return { inArray, // 列舉類 SettingKeyEnum, // 正在載入 isLoading: true, // 首次載入 isFirstload: true, // 是否已登入 isLogin: false, // 系統設定 setting: {}, // 當前使用者資訊 userInfo: {}, // 賬戶資產 assets: { balance: '--', points: '--', coupon: '--' }, // 我的服務 service, // 訂單操作 orderNavbar, // 當前使用者待處理的訂單數量 todoCounts: { payment: 0, deliver: 0, received: 0 } } }, /** * 生命週期函式--監聽頁面顯示 */ onLoad(options) {}, /** * 生命週期函式--監聽頁面顯示 */ onShow(options) { this.onRefreshPage() }, methods: { // 重新整理頁面 onRefreshPage() { // 更新購物車角標 setCartTabBadge() // 判斷是否已登入 this.isLogin = checkLogin() // 獲取頁面資料 this.getPageData() }, // 獲取頁面資料 getPageData(callback) { const app = this app.isLoading = true Promise.all([app.getSetting(), app.getUserInfo(), app.getUserAssets(), app.getTodoCounts()]) .then(result => { app.isFirstload = false // 初始化我的服務資料 app.initService() // 初始化訂單運算元據 app.initOrderTabbar() // 執行回撥函式 callback && callback() }) .catch(err => console.log('catch', err)) .finally(() => app.isLoading = false) }, // 初始化我的服務資料 async initService() { const app = this const isShowCustomerBtn = await SettingModel.isShowCustomerBtn() const newService = [] service.forEach(item => { // 預設開啟 item.enabled = true // 我的積分 if (item.id === 'points') { item.name = '我的' + app.setting[SettingKeyEnum.POINTS.value].points_name } // 企業微信客服 if (item.id === 'contact' && !isShowCustomerBtn) { item.enabled = false } // 資料角標 if (item.count != undefined) { item.count = app.todoCounts[item.id] } newService.push(item) }) app.service = filterModules(newService) }, // 初始化訂單運算元據 initOrderTabbar() { const app = this const newOrderNavbar = [] orderNavbar.forEach(item => { if (item.count != undefined) { item.count = app.todoCounts[item.id] } newOrderNavbar.push(item) }) app.orderNavbar = newOrderNavbar }, // 獲取商城設定 getSetting() { const app = this return new Promise((resolve, reject) => { SettingModel.data() .then(setting => { app.setting = setting resolve(setting) }) .catch(reject) }) }, // 獲取當前使用者資訊 getUserInfo() { const app = this return new Promise((resolve, reject) => { !app.isLogin ? resolve(null) : UserApi.info({}, { load: app.isFirstload }) .then(result => { app.userInfo = result.data.userInfo resolve(app.userInfo) }) .catch(err => { if (err.result && err.result.status == 401) { app.isLogin = false resolve(null) } else { reject(err) } }) }) }, // 獲取賬戶資產 getUserAssets() { const app = this return new Promise((resolve, reject) => { !app.isLogin ? resolve(null) : UserApi.assets({}, { load: app.isFirstload }) .then(result => { app.assets = result.data.assets resolve(app.assets) }) .catch(err => { if (err.result && err.result.status == 401) { app.isLogin = false resolve(null) } else { reject(err) } }) }) }, // 獲取當前使用者待處理的訂單數量 getTodoCounts() { const app = this return new Promise((resolve, reject) => { !app.isLogin ? resolve(null) : OrderApi.todoCounts({}, { load: app.isFirstload }) .then(result => { app.todoCounts = result.data.counts resolve(app.todoCounts) }) .catch(err => { if (err.result && err.result.status == 401) { app.isLogin = false resolve(null) } else { reject(err) } }) }) }, // 跳轉到登入頁 handleLogin() { !this.isLogin && this.$navTo('pages/login/index') }, // 跳轉到繫結手機號頁面 handleBindMobile() { this.$navTo('pages/user/bind/index') }, // 跳轉到修改個人資訊頁 handlePersonal() { this.$navTo('pages/user/personal/index') }, // 退出登入 handleLogout() { const app = this uni.showModal({ title: '友情提示', content: '您確定要退出登入嗎?', success(res) { if (res.confirm) { store.dispatch('Logout', {}) .then(result => app.onRefreshPage()) } } }) }, // 跳轉到錢包頁面 onTargetWallet() { this.$navTo('pages/wallet/index') }, // 跳轉到訂單頁 onTargetOrder(item) { this.$navTo('pages/order/index', { dataType: item.id }) }, // 跳轉到我的積分頁面 onTargetPoints() { this.$navTo('pages/points/log') }, // 跳轉到我的優惠券頁 onTargetMyCoupon() { this.$navTo('pages/my-coupon/index') }, // 跳轉到服務頁面 handleService({ url }) { this.$navTo(url) } }, /** * 下拉重新整理 */ onPullDownRefresh() { // 獲取首頁資料 this.getPageData(() => { uni.stopPullDownRefresh() }) }, } </script> <style lang="scss" scoped> .container { padding-bottom: 60rpx; } // 頁面頭部 .main-header { // background-color: #FBF7EF; position: relative; width: 100%; height: 280rpx; background-size: 100% 100%; overflow: hidden; display: flex; align-items: center; padding-left: 30rpx; .bg-image { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 0; } .user-info { display: flex; height: 100rpx; z-index: 1; .user-content { display: flex; flex-direction: column; justify-content: center; margin-left: 30rpx; color: #c59a46; .nick-name { font-size: 34rpx; font-weight: bold; max-width: 300rpx; } .mobile { margin-top: 15rpx; font-size: 28rpx; } .user-grade { align-self: baseline; display: flex; align-items: center; background: #3c3c3c; margin-top: 12rpx; border-radius: 10rpx; padding: 4rpx 12rpx; .user-grade_icon .image { display: block; width: 32rpx; height: 32rpx; } .user-grade_name { margin-left: 5rpx; font-size: 26rpx; color: #EEE0C3; } } .login-tips { margin-top: 12rpx; font-size: 30rpx; } } } } // 角標元件 .item-badge { position: absolute; top: 0; right: 55rpx; // background: $main-bg; background: #fa2209; color: #fff; border-radius: 100%; min-width: 38rpx; height: 38rpx; display: flex; justify-content: center; align-items: center; padding: 1rpx; font-size: 24rpx; } // 我的錢包 .my-asset { display: flex; background: #fff; padding: 40rpx 0; .asset-right { width: 200rpx; border-left: 1rpx solid #eee; } .asset-right-item { text-align: center; color: #545454; .item-icon { font-size: 44rpx; } .item-name { margin-top: 14rpx; font-size: 28rpx; } } .asset-left-item { max-width: 183rpx; text-align: center; color: #666; padding: 0 16rpx; .item-value { font-size: 34rpx; color: $main-bg; } .item-name { margin-top: 14rpx; font-size: 28rpx; } } } // 訂單操作 .order-navbar { display: flex; margin: 20rpx auto 20rpx auto; padding: 20rpx 0 26rpx 0; width: 94%; box-shadow: 0 1rpx 5rpx 0px rgba(0, 0, 0, 0.05); font-size: 30rpx; border-radius: 5rpx; background: #fff; &-item { position: relative; width: 25%; .item-icon { text-align: center; margin: 0 auto; padding: 10rpx 0; color: #545454; font-size: 44rpx; } .item-name { font-size: 28rpx; color: #545454; text-align: center; margin-right: 10rpx; } } } // 我的服務 .my-service { margin: 22rpx auto 22rpx auto; padding: 22rpx 0; width: 94%; box-shadow: 0 1rpx 5rpx 0px rgba(0, 0, 0, 0.05); border-radius: 5rpx; background: #fff; .service-title { padding-left: 24rpx; margin-bottom: 20rpx; font-size: 30rpx; } .service-content { margin-bottom: -20rpx; .service-item { position: relative; width: 25%; float: left; margin-bottom: 30rpx; .item-icon { text-align: center; margin: 0 auto; padding: 14rpx 0; color: $main-bg; font-size: 44rpx; } .item-name { font-size: 28rpx; color: #545454; text-align: center; } } } } // 退出登入 .my-logout { display: flex; justify-content: center; margin-top: 50rpx; .logout-btn { width: 60%; margin: 0 auto; font-size: 28rpx; color: #616161; border-radius: 20rpx; border: 1px solid #dcdcdc; padding: 16rpx 0; text-align: center; } } // 繫結手機號 樣式1 .my-mobile { display: flex; justify-content: space-between; align-items: center; padding: 16rpx 40rpx; background: #FCEBD1; .info { color: #cd8c0c; font-size: 28rpx; } .btn-bind { padding: 8rpx 24rpx; background-color: #EAB766; color: #fff; border-radius: 30rpx; font-size: 26rpx; text-align: center; } } // 繫結手機號 樣式2 .my-mobile2 { display: flex; justify-content: space-between; align-items: center; margin: 20rpx auto 20rpx auto; padding: 12rpx 40rpx; width: 94%; box-shadow: 0 1rpx 5rpx 0px rgba(0, 0, 0, 0.05); font-size: 30rpx; border-radius: 5rpx; background: #fff; .info { // color: #cd8c0c; font-size: 26rpx; } .btn-bind { padding: 8rpx 24rpx; background-color: #EAB766; color: #fff; border-radius: 30rpx; font-size: 26rpx; text-align: center; } } </style>
三、專案總結
由於篇幅原因,更多資訊和原始碼可直接聯絡本人微信(red_tea_v2),程式碼和服務部署可以提供技術支援,其他問題可直接在文章下面評論。