This commit is contained in:
solosw
2026-01-05 14:11:34 +08:00
parent 35ef825371
commit 99b11b04e4
658 changed files with 99266 additions and 0 deletions
+73
View File
@@ -0,0 +1,73 @@
<script>
export default {
onLaunch: function() {
console.log('App Launch')
this.checkNetworkStatus()
},
onShow: function() {
console.log('App Show')
this.checkNetworkStatus()
},
onHide: function() {
console.log('App Hide')
},
methods: {
// 检查网络状态
checkNetworkStatus() {
uni.getNetworkType({
success: (res) => {
console.log('网络类型:', res.networkType)
if (res.networkType === 'none') {
uni.showModal({
title: '网络连接失败',
content: '请检查您的网络连接后重试',
showCancel: false,
confirmText: '知道了'
})
}
},
fail: (err) => {
console.error('获取网络状态失败:', err)
}
})
// 监听网络状态变化
uni.onNetworkStatusChange((res) => {
console.log('网络状态变化:', res)
if (!res.isConnected) {
uni.showToast({
title: '网络连接已断开',
icon: 'none',
duration: 3000
})
} else {
uni.showToast({
title: '网络连接已恢复',
icon: 'success',
duration: 2000
})
}
})
}
}
}
</script>
<style lang="scss">
/*每个页面公共css */
@import '@/uni_modules/uni-scss/index.scss';
/* #ifndef APP-NVUE */
@import '@/static/customicons.css';
// 设置整个项目的背景色
page {
background-color: #f5f5f5;
}
/* #endif */
.example-info {
font-size: 14px;
color: #333;
padding: 10px;
}
</style>
+3
View File
@@ -0,0 +1,3 @@
{
"prompt" : "none"
}
BIN
View File
Binary file not shown.
+284
View File
@@ -0,0 +1,284 @@
<template>
<view>
<view class="list" :style="{width:width+'rpx',height:height+'rpx'}">
<picker class="picker" mode="multiSelector" :range="region" range-key="name" :value="regionIndex" @change="pickerChange"
@columnchange="pickerColumnchange">
<view class="pbox" :class="{'pbox_hover':regionStr != '请选择省市区'}">
<view>{{regionStr}}</view>
<text class="iconfont icon-you"></text>
</view>
</picker>
</view>
</view>
</template>
<script>
import region from './pca-code.json';
export default {
data() {
return {
// 原数组
oldRegion: region,
// 处理后的数组
region: [
[],
[],
[]
],
// 选择省市区的下标Index 传则默认选中传递的
regionIndex: [0, 0, 0],
// 选择的id
// previnceId: 11,
// cityId: 1101,
// countyId: 110101,
// 省市区字符串
regionStr: '请选择省/市/区'
};
},
props: {
// 组件高度
height: {
type: [Number],
default: 92
},
// 组件宽度
width: {
type: [Number],
default: 710
},
// 省id
previnceId: {
type: [Number],
default: 11
},
// 城市id
cityId: {
type: [Number],
default: 1101
},
// 县区id
countyId: {
type: [Number],
default: 110101
},
// 是否是为修改(true为修改)
isRevise: {
type: [Boolean],
default: true
},
// 是否显示"全部区"选项
showAllDistrict: {
type: [Boolean],
default: true
}
},
methods: {
pickerChange(e) {
// console.log(e, '1');
this.regionIndex = e.detail.value;
const provinceName = this.region[0][this.regionIndex[0]].name;
const cityName = this.region[1][this.regionIndex[1]].name;
let countyName = '';
// 如果开启了全部区功能且选择的是第一项"全部"
if (this.showAllDistrict && this.regionIndex[2] === 0 && this.region[2][0] && this.region[2][0].name === '全部') {
countyName = '全部';
this.regionStr = provinceName + ' ' + cityName + ' ' + countyName;
} else {
// 正常情况下直接使用选择的项
if (this.region[2][this.regionIndex[2]]) {
countyName = this.region[2][this.regionIndex[2]].name;
this.regionStr = provinceName + ' ' + cityName + ' ' + countyName;
}
}
// 组件传值 - 如果选择了"全部",则传递空字符串给区
const emitCountyName = countyName === '全部' ? '' : countyName;
this.$emit('region', [provinceName, cityName, emitCountyName]);
},
pickerColumnchange(e) {
// console.log(e);
// 第几列滑动
// console.log(e.detail.column);
// 第几列滑动的下标
// console.log(e.detail.value)
if (e.detail.column === 0) {
// 声明城市数组
let cityArr = [];
let countyArr = [];
// 设置下标
this.regionIndex = [e.detail.value, 0, 0];
// 改变城市列表
this.region[1] = this.oldRegion[e.detail.value].children.map(item => {
cityArr.push({
name: item.name,
code: item.code
});
})
this.$set(this.region, 1, cityArr);
// 改变县区列表 - 如果开启了全部区功能,首先添加"全部"选项
if (this.showAllDistrict) {
countyArr.push({
name: '全部',
code: -1
});
}
this.oldRegion[e.detail.value].children[0].children.map(item => {
countyArr.push({
name: item.name,
code: item.code
});
})
this.$set(this.region, 2, countyArr);
}
if (e.detail.column === 1) {
this.regionIndex[1] = e.detail.value;
this.regionIndex[2] = 0;
let countyArr = [];
// 如果开启了全部区功能,首先添加"全部"选项
if (this.showAllDistrict) {
countyArr.push({
name: '全部',
code: -1
});
}
this.oldRegion[this.regionIndex[0]].children[this.regionIndex[1]].children.map(item => {
countyArr.push({
name: item.name,
code: item.code
});
})
this.$set(this.region, 2, countyArr);
}
if (e.detail.column === 2) {
this.regionIndex[2] = e.detail.value;
}
}
},
created() {
let provinceArr = [];
let cityArr = [];
this.oldRegion.map((item, index) => {
this.region[0].push({
name: item.name,
code: item.code
});
if (this.previnceId == item.code) {
provinceArr = item.children;
this.regionIndex[0] = index;
}
})
// console.log(provinceArr);
provinceArr.map((item, index) => {
this.region[1].push({
name: item.name,
code: item.code
});
if (this.cityId == item.code) {
cityArr = item.children;
this.regionIndex[1] = index;
}
})
// 如果开启了全部区功能,首先添加"全部"选项到区列表
if (this.showAllDistrict) {
this.region[2].push({
name: '全部',
code: -1
});
}
cityArr.map((item, index) => {
this.region[2].push({
name: item.name,
code: item.code
});
if (this.countyId == item.code) {
// 如果开启了全部区功能,index要+1,因为前面插入了"全部"
this.regionIndex[2] = this.showAllDistrict ? index + 1 : index;
}
})
// 如果传入的countyId为-1且开启了全部区功能,则选中"全部"
if (this.countyId == -1 && this.showAllDistrict) {
this.regionIndex[2] = 0;
}
if (this.isRevise) {
this.regionStr = this.region[0][this.regionIndex[0]].name + ' ' + this.region[1][this.regionIndex[1]].name + ' ' +
this.region[2][this.regionIndex[2]].name;
} else {
this.regionStr = '请选择省市区';
}
}
}
</script>
<style lang="scss">
.list {
// border-bottom: 1rpx solid #eee;
padding: 0 8rpx;
box-sizing: border-box;
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
position: relative;
.picker {
flex: 1;
height: 92rpx;
.pbox {
width: 100%;
height: 92rpx;
display: flex;
flex-direction: row;
align-items: center;
justify-content: space-between;
color: #808080;
view{
width: 100%;
text-align: right;
}
.icon-you {
font-size: 28rpx;
}
}
.pbox_hover {
color: #383838;
}
}
.name {
width: 168rpx;
font-size: 32rpx;
color: #383838;
}
.icon-you {
font-size: 28rpx;
color: #999999;
}
.input {
flex: 1;
height: 100%;
line-height: 92rpx;
color: #9080A1;
}
.textarea {
flex: 1;
height: 100%;
color: #A9A9A9;
}
}
</style>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+24
View File
@@ -0,0 +1,24 @@
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<title>
<%= htmlWebpackPlugin.options.title %>
</title>
<script>
document.addEventListener('DOMContentLoaded', function() {
document.documentElement.style.fontSize = document.documentElement.clientWidth / 20 + 'px'
})
</script>
<link rel="stylesheet" href="<%= BASE_URL %>static/index.css" />
<!-- 图片看自己喜好放在哪个文件下面 -->
<link rel="icon" href="/static/icon.jpg" />
</head>
<body>
<noscript>
<strong>Please enable JavaScript to continue.</strong>
</noscript>
<div id="app"></div>
</body>
</html>
+20
View File
@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<script>
var coverSupport = 'CSS' in window && typeof CSS.supports === 'function' && (CSS.supports('top: env(a)') ||
CSS.supports('top: constant(a)'))
document.write(
'<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0' +
(coverSupport ? ', viewport-fit=cover' : '') + '" />')
</script>
<title></title>
<!--preload-links-->
<!--app-context-->
</head>
<body>
<div id="app"><!--app-html--></div>
<script type="module" src="/main.js"></script>
</body>
</html>
+25
View File
@@ -0,0 +1,25 @@
// #ifndef VUE3
import Vue from 'vue'
import App from './App'
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
// #endif
// #ifdef VUE3
import { createSSRApp } from 'vue'
import App from './App.vue'
export function createApp() {
const app = createSSRApp(App)
return {
app
}
}
// #endif
+121
View File
@@ -0,0 +1,121 @@
{
"name" : "businesshelp",
"appid" : "__UNI__0B7CED5",
"description" : "",
"versionName" : "1.0.0",
"versionCode" : "100",
"transformPx" : false,
"app-plus" : {
/* 5+App特有相关 */
"usingComponents" : true,
"nvueCompiler" : "uni-app",
"nvueStyleCompiler" : "uni-app",
"splashscreen" : {
"alwaysShowBeforeRender" : true,
"waiting" : true,
"autoclose" : true,
"delay" : 0
},
"modules" : {
"Contacts" : {}
},
/* 模块配置 */
"distribute" : {
/* 应用发布信息 */
"android" : {
/* android打包配置 */
"permissions" : [
"<uses-permission android:name=\"android.permission.CHANGE_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.MOUNT_UNMOUNT_FILESYSTEMS\"/>",
"<uses-permission android:name=\"android.permission.VIBRATE\"/>",
"<uses-permission android:name=\"android.permission.READ_LOGS\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_WIFI_STATE\"/>",
"<uses-feature android:name=\"android.hardware.camera.autofocus\"/>",
"<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\"/>",
"<uses-permission android:name=\"android.permission.CAMERA\"/>",
"<uses-permission android:name=\"android.permission.GET_ACCOUNTS\"/>",
"<uses-permission android:name=\"android.permission.READ_PHONE_STATE\"/>",
"<uses-permission android:name=\"android.permission.CHANGE_WIFI_STATE\"/>",
"<uses-permission android:name=\"android.permission.WAKE_LOCK\"/>",
"<uses-permission android:name=\"android.permission.FLASHLIGHT\"/>",
"<uses-feature android:name=\"android.hardware.camera\"/>",
"<uses-permission android:name=\"android.permission.WRITE_SETTINGS\"/>",
"<uses-permission android:name=\"android.permission.INTERNET\"/>"
],
"abiFilters" : [ "armeabi-v7a", "arm64-v8a", "x86" ],
"schemes" : [ "businesshelp" ],
"minSdkVersion" : 21,
"targetSdkVersion" : 28,
"usesCleartextTraffic" : true
},
"ios" : {},
/* ios打包配置 */
"sdkConfigs" : {},
"splashscreen" : {
"androidStyle" : "common",
"android" : {
"hdpi" : "static/profile.png",
"xhdpi" : "static/profile.png",
"xxhdpi" : "static/profile.png"
},
"useOriginalMsgbox" : false
},
"icons" : {
"android" : {
"hdpi" : "unpackage/res/icons/72x72.png",
"xhdpi" : "unpackage/res/icons/96x96.png",
"xxhdpi" : "unpackage/res/icons/144x144.png",
"xxxhdpi" : "unpackage/res/icons/192x192.png"
},
"ios" : {
"appstore" : "unpackage/res/icons/1024x1024.png",
"ipad" : {
"app" : "unpackage/res/icons/76x76.png",
"app@2x" : "unpackage/res/icons/152x152.png",
"notification" : "unpackage/res/icons/20x20.png",
"notification@2x" : "unpackage/res/icons/40x40.png",
"proapp@2x" : "unpackage/res/icons/167x167.png",
"settings" : "unpackage/res/icons/29x29.png",
"settings@2x" : "unpackage/res/icons/58x58.png",
"spotlight" : "unpackage/res/icons/40x40.png",
"spotlight@2x" : "unpackage/res/icons/80x80.png"
},
"iphone" : {
"app@2x" : "unpackage/res/icons/120x120.png",
"app@3x" : "unpackage/res/icons/180x180.png",
"notification@2x" : "unpackage/res/icons/40x40.png",
"notification@3x" : "unpackage/res/icons/60x60.png",
"settings@2x" : "unpackage/res/icons/58x58.png",
"settings@3x" : "unpackage/res/icons/87x87.png",
"spotlight@2x" : "unpackage/res/icons/80x80.png",
"spotlight@3x" : "unpackage/res/icons/120x120.png"
}
}
}
}
},
/* SDK配置 */
"quickapp" : {},
/* 快应用特有相关 */
"mp-weixin" : {
/* 小程序特有相关 */
"appid" : "",
"setting" : {
"urlCheck" : false
},
"usingComponents" : true
},
"vueVersion" : "2",
"locale" : "zh-Hans",
"h5" : {
"router" : {
"base" : "/h5",
"mode" : "history"
},
"title" : "商帮帮",
"devServer" : {
"https" : false
},
"template" : "count.html"
}
}
+16
View File
@@ -0,0 +1,16 @@
{
"id": "zxp-uniRegionSheet",
"name": "省市区选择器 内置数据",
"displayName": "省市区选择器 内置数据",
"version": "1.1",
"description": "省市区选择器 面包屑",
"keywords": [
"省市区三级联动"
],
"dcloudext": {
"category": [
"前端组件",
"通用组件"
]
}
}
+165
View File
@@ -0,0 +1,165 @@
{
"pages": [
{
"path": "pages/login/login",
"style": {
"navigationBarTitleText": "登录"
}
},
{
"path": "pages/index/index",
"style": {
"navigationBarTitleText": "首页",
"navigationBarBackgroundColor": "#FF4444",
"navigationBarTextStyle": "white"
}
},
{
"path": "pages/mall/mall",
"style": {
"navigationBarTitleText": "商品列表",
"navigationBarBackgroundColor": "#FF4444",
"navigationBarTextStyle": "white"
},
"enablePullDownRefresh":true
},
{
"path": "pages/orders/orders",
"style": {
"navigationBarTitleText": "我的买单",
"navigationBarBackgroundColor": "#FF4444",
"navigationBarTextStyle": "white"
}
},
{
"path": "pages/sales/sales",
"style": {
"navigationBarTitleText": "我的卖单",
"navigationBarBackgroundColor": "#FF4444",
"navigationBarTextStyle": "white"
}
},
{
"path": "pages/warehouse/warehouse",
"style": {
"navigationBarTitleText": "我的仓库",
"navigationBarBackgroundColor": "#FF4444",
"navigationBarTextStyle": "white"
}
},
{
"path": "pages/profile/profile",
"style": {
"navigationBarTitleText": "个人中心",
"navigationBarBackgroundColor": "#FF4444",
"navigationBarTextStyle": "white"
}
},
{
"path": "pages/register/register",
"style": {
"navigationBarTitleText": "注册"
}
},
{
"path": "pages/address/address",
"style": {
"navigationBarTitleText": "我的地址"
}
},
{
"path": "pages/address/edit",
"style": {
"navigationBarTitleText": "编辑地址"
}
},
{
"path": "pages/payment/payment",
"style": {
"navigationBarTitleText": "收款方式"
}
},
{
"path": "pages/product/detail",
"style": {
"navigationBarTitleText": "商品详情"
}
},
{
"path": "pages/payment/purchase",
"style": {
"navigationBarTitleText": "付款"
}
},
{
"path": "pages/scores/scores",
"style": {
"navigationBarTitleText": "积分明细"
}
},
{
"path": "pages/orders/detail",
"style": {
"navigationBarTitleText": "订单详情"
}
},
{
"path": "pages/reconciliation/reconciliation",
"style": {
"navigationBarTitleText": "对账管理",
"navigationBarBackgroundColor": "#FF4444",
"navigationBarTextStyle": "white"
}
},
{
"path": "pages/profile/edit",
"style": {
"navigationBarTitleText": "个人信息",
"navigationBarBackgroundColor": "#FF4444",
"navigationBarTextStyle": "white"
}
}
],
"tabBar": {
"color": "#999999",
"selectedColor": "#FF4444",
"backgroundColor": "#ffffff",
"borderStyle": "black",
"list": [
{
"pagePath": "pages/index/index",
"iconPath": "static/home.png",
"selectedIconPath": "static/home.png",
"text": "首页"
},
{
"pagePath": "pages/mall/mall",
"iconPath": "static/mall.png",
"selectedIconPath": "static/mall.png",
"text": "商城"
},
{
"pagePath": "pages/profile/profile",
"iconPath": "static/profile.png",
"selectedIconPath": "static/profile.png",
"text": "我的"
}
]
},
"globalStyle": {
"navigationBarTextStyle": "white",
"navigationBarTitleText": "商城",
"navigationBarBackgroundColor": "#FF4444",
"backgroundColor": "#F5F5F5"
}
}
+374
View File
@@ -0,0 +1,374 @@
<template>
<view class="container">
<!-- 页面标题 -->
<view class="page-header">
<text class="page-title">收货地址</text>
<view class="add-btn" @tap="addAddress">
<uni-icons type="plus" size="20" color="white"></uni-icons>
<text class="add-text">新增地址</text>
</view>
</view>
<!-- 地址列表 -->
<view class="address-list" v-if="!loading && addressList.length > 0">
<view class="address-item" v-for="(address, index) in addressList" :key="address.id">
<!-- 默认标签 -->
<view class="default-tag" v-if="address.is_default === 1">
<text class="default-text">默认</text>
</view>
<!-- 地址信息 -->
<view class="address-content" @tap="editAddress(address)">
<view class="address-header">
<text class="consignee-name">{{ address.consignee_name }}</text>
<text class="consignee-phone">{{ address.consignee_phone }}</text>
</view>
<view class="address-detail">
<text class="address-text">{{ formatAddress(address) }}</text>
</view>
</view>
<!-- 操作按钮 -->
<view class="address-actions">
<view class="action-btn default-btn"
v-if="address.is_default !== 1"
@tap="setDefaultAddress(address.id)">
<text class="action-text">设为默认</text>
</view>
<view class="action-btn edit-btn" @tap="editAddress(address)">
<text class="action-text">编辑</text>
</view>
<view class="action-btn delete-btn" @tap="deleteAddress(address.id, index)">
<text class="action-text">删除</text>
</view>
</view>
</view>
</view>
<!-- 空状态 -->
<view class="empty-state" v-if="!loading && addressList.length === 0">
<uni-icons type="location" size="100" color="#ccc"></uni-icons>
<text class="empty-text">暂无收货地址</text>
<button class="add-first-btn" @tap="addAddress">添加收货地址</button>
</view>
<!-- 加载状态 -->
<view class="loading-state" v-if="loading">
<text class="loading-text">加载中...</text>
</view>
</view>
</template>
<script>
import request from '@/utils/request.js'
export default {
data() {
return {
addressList: [],
loading: false
}
},
onLoad() {
// 检查登录状态
const token = uni.getStorageSync('token')
if (!token) {
uni.reLaunch({
url: '/pages/login/login'
})
return
}
this.loadAddressList()
},
onShow() {
// 页面显示时重新加载地址列表(用于从编辑页面返回时刷新)
this.loadAddressList()
},
methods: {
// 加载地址列表
async loadAddressList() {
this.loading = true
try {
const res = await request.get('/back/user/addresses')
if (res.success) {
this.addressList = res.data || []
}
} catch (error) {
console.error('加载地址列表失败:', error)
uni.showToast({
title: '加载失败',
icon: 'none'
})
} finally {
this.loading = false
}
},
// 格式化地址
formatAddress(address) {
return `${address.province} ${address.city} ${address.district} ${address.detail_address}`
},
// 新增地址
addAddress() {
uni.navigateTo({
url: '/pages/address/edit'
})
},
// 编辑地址
editAddress(address) {
uni.navigateTo({
url: `/pages/address/edit?id=${address.id}`
})
},
// 设置默认地址
async setDefaultAddress(addressId) {
try {
uni.showLoading({
title: '设置中...',
mask: true
})
const res = await request.put(`/back/user/addresses/${addressId}/default`)
if (res.success) {
uni.showToast({
title: '设置成功',
icon: 'success'
})
// 重新加载地址列表
this.loadAddressList()
} else {
throw new Error(res.message || '设置失败')
}
} catch (error) {
console.error('设置默认地址失败:', error)
uni.showToast({
title: '设置失败',
icon: 'none'
})
} finally {
uni.hideLoading()
}
},
// 删除地址
deleteAddress(addressId, index) {
uni.showModal({
title: '确认删除',
content: '确定要删除这个收货地址吗?',
success: async (res) => {
if (res.confirm) {
await this.confirmDeleteAddress(addressId, index)
}
}
})
},
// 确认删除地址
async confirmDeleteAddress(addressId, index) {
try {
uni.showLoading({
title: '删除中...',
mask: true
})
const res = await request.delete(`/back/user/addresses/${addressId}`)
if (res.success) {
// 从列表中移除
this.addressList.splice(index, 1)
uni.showToast({
title: '删除成功',
icon: 'success'
})
} else {
throw new Error(res.message || '删除失败')
}
} catch (error) {
console.error('删除地址失败:', error)
uni.showToast({
title: '删除失败',
icon: 'none'
})
} finally {
uni.hideLoading()
}
}
}
}
</script>
<style scoped>
.container {
background-color: #f5f5f5;
min-height: 100vh;
}
.page-header {
background: white;
padding: 30rpx;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1rpx solid #eee;
}
.page-title {
font-size: 36rpx;
font-weight: bold;
color: #333;
}
.add-btn {
background: linear-gradient(135deg, #FF4444 0%, #FF6666 100%);
padding: 15rpx 25rpx;
border-radius: 30rpx;
display: flex;
align-items: center;
gap: 8rpx;
}
.add-text {
color: white;
font-size: 26rpx;
font-weight: bold;
}
.address-list {
padding: 20rpx;
}
.address-item {
background: white;
border-radius: 20rpx;
margin-bottom: 20rpx;
overflow: hidden;
position: relative;
}
.default-tag {
position: absolute;
top: 20rpx;
right: 20rpx;
background: #FF4444;
padding: 8rpx 16rpx;
border-radius: 20rpx;
z-index: 1;
}
.default-text {
color: white;
font-size: 22rpx;
font-weight: bold;
}
.address-content {
padding: 30rpx;
padding-right: 100rpx;
}
.address-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15rpx;
}
.consignee-name {
font-size: 32rpx;
font-weight: bold;
color: #333;
}
.consignee-phone {
font-size: 28rpx;
color: #666;
}
.address-detail {
margin-bottom: 20rpx;
}
.address-text {
font-size: 28rpx;
color: #666;
line-height: 1.6;
}
.address-actions {
display: flex;
border-top: 1rpx solid #eee;
}
.action-btn {
flex: 1;
padding: 25rpx;
text-align: center;
border-right: 1rpx solid #eee;
}
.action-btn:last-child {
border-right: none;
}
.default-btn {
background: #f8f8f8;
}
.edit-btn {
background: #f0f8ff;
}
.delete-btn {
background: #fff0f0;
}
.action-text {
font-size: 26rpx;
color: #333;
}
.delete-btn .action-text {
color: #FF4444;
}
.edit-btn .action-text {
color: #1890ff;
}
.empty-state {
padding: 100rpx 50rpx;
text-align: center;
background: white;
margin: 20rpx;
border-radius: 20rpx;
}
.empty-text {
font-size: 28rpx;
color: #999;
margin: 30rpx 0;
display: block;
}
.add-first-btn {
background: linear-gradient(135deg, #FF4444 0%, #FF6666 100%);
color: white;
border: none;
border-radius: 30rpx;
padding: 20rpx 40rpx;
font-size: 28rpx;
font-weight: bold;
}
.loading-state {
padding: 100rpx;
text-align: center;
}
.loading-text {
font-size: 28rpx;
color: #999;
}
</style>
+392
View File
@@ -0,0 +1,392 @@
<template>
<view class="container">
<!-- 页面标题 -->
<view class="page-header">
<text class="page-title">{{ isEdit ? '编辑地址' : '新增地址' }}</text>
</view>
<!-- 地址表单 -->
<view class="form-container">
<!-- 收件人信息 -->
<view class="form-section">
<view class="section-title">收件人信息</view>
<view class="form-item">
<text class="form-label">收件人姓名</text>
<input class="form-input"
type="text"
v-model="formData.consignee_name"
placeholder="请输入收件人姓名"
maxlength="20">
</view>
<view class="form-item">
<text class="form-label">手机号码</text>
<input class="form-input"
type="number"
v-model="formData.consignee_phone"
placeholder="请输入手机号码"
maxlength="11">
</view>
</view>
<!-- 收货地址 -->
<view class="form-section">
<view class="section-title">收货地址</view>
<view class="form-item">
<text class="form-label">所在地区</text>
<view class="region-container">
<Region
:width="420"
:height="92"
:showAllDistrict="false"
:isRevise="hasSelectedRegion"
:previnceId="provinceId"
:cityId="cityId"
:countyId="countyId"
@region="onRegionChange"
/>
</view>
</view>
<view class="form-item">
<text class="form-label">详细地址</text>
<textarea class="form-textarea"
v-model="formData.detail_address"
placeholder="请输入详细地址,如道路、门牌号、小区、楼栋号等"
maxlength="200"
auto-height>
</textarea>
</view>
<view class="form-item">
<text class="form-label">邮政编码</text>
<input class="form-input"
type="text"
v-model="formData.postal_code"
placeholder="请输入邮政编码(可选)"
maxlength="6">
</view>
</view>
<!-- 默认地址设置 -->
<view class="form-section">
<view class="form-item no-border">
<text class="form-label">设为默认地址</text>
<switch :checked="formData.is_default === 1" @change="onDefaultChange"></switch>
</view>
</view>
</view>
<!-- 保存按钮 -->
<view class="save-section">
<button class="save-btn" @tap="saveAddress" :disabled="saving">
<text v-if="saving">保存中...</text>
<text v-else>{{ isEdit ? '保存修改' : '保存地址' }}</text>
</button>
</view>
</view>
</template>
<script>
import request from '@/utils/request.js'
import Region from '@/components/k-region.vue'
export default {
components:{
Region
},
data() {
return {
isEdit: false,
addressId: null,
formData: {
consignee_name: '',
consignee_phone: '',
province: '',
city: '',
district: '',
detail_address: '',
postal_code: '',
is_default: 0
},
saving: false,
// k-region组件需要的数据
provinceId: 11, // 默认北京
cityId: 1101, // 默认北京市
countyId: 110101 // 默认东城区
}
},
computed: {
regionText() {
if (this.formData.province && this.formData.city && this.formData.district) {
return `${this.formData.province} ${this.formData.city} ${this.formData.district}`
}
return ''
},
hasSelectedRegion() {
return !!(this.formData.province && this.formData.city && this.formData.district)
}
},
onLoad(options) {
// 检查登录状态
const token = uni.getStorageSync('token')
if (!token) {
uni.reLaunch({
url: '/pages/login/login'
})
return
}
// 判断是编辑还是新增
if (options.id) {
this.isEdit = true
this.addressId = options.id
this.loadAddressDetail()
}
},
methods: {
// 加载地址详情
async loadAddressDetail() {
try {
const res = await request.get(`/back/user/addresses/${this.addressId}`)
if (res.success) {
this.formData = res.data
// 转换地区名称为代码(这里需要添加映射逻辑,暂时使用默认值)
this.updateRegionCodes()
}
} catch (error) {
console.error('加载地址详情失败:', error)
uni.showToast({
title: '加载失败',
icon: 'none'
})
}
},
// 更新地区代码(根据地区名称)
updateRegionCodes() {
// 这里可以添加地区名称到代码的映射逻辑
// 暂时使用默认值,实际应用中需要完整的地区代码映射表
if (this.formData.province && this.formData.city && this.formData.district) {
// 如果有具体的映射需求,可以在这里添加
// 例如:this.provinceId = getProvinceCodeByName(this.formData.province)
}
},
// k-region组件回调
onRegionChange(regionArray) {
console.log('选择的地区:', regionArray)
this.formData.province = regionArray[0] || ''
this.formData.city = regionArray[1] || ''
this.formData.district = regionArray[2] || ''
},
// 默认地址开关变化
onDefaultChange(e) {
this.formData.is_default = e.detail.value ? 1 : 0
},
// 表单验证
validateForm() {
if (!this.formData.consignee_name.trim()) {
uni.showToast({
title: '请输入收件人姓名',
icon: 'none'
})
return false
}
if (!this.formData.consignee_phone.trim()) {
uni.showToast({
title: '请输入手机号码',
icon: 'none'
})
return false
}
const phoneReg = /^1[3-9]\d{9}$/
if (!phoneReg.test(this.formData.consignee_phone)) {
uni.showToast({
title: '请输入正确的手机号码',
icon: 'none'
})
return false
}
if (!this.formData.province || !this.formData.city || !this.formData.district) {
uni.showToast({
title: '请选择所在地区',
icon: 'none'
})
return false
}
if (!this.formData.detail_address.trim()) {
uni.showToast({
title: '请输入详细地址',
icon: 'none'
})
return false
}
return true
},
// 保存地址
async saveAddress() {
if (!this.validateForm()) {
return
}
this.saving = true
try {
let res
if (this.isEdit) {
res = await request.put(`/back/user/addresses/${this.addressId}`, this.formData)
} else {
res = await request.post('/back/user/addresses', this.formData)
}
if (res.success) {
uni.showToast({
title: this.isEdit ? '修改成功' : '添加成功',
icon: 'success'
})
// 延迟返回上一页
setTimeout(() => {
uni.navigateBack()
}, 1500)
} else {
throw new Error(res.message || '保存失败')
}
} catch (error) {
console.error('保存地址失败:', error)
uni.showToast({
title: '保存失败',
icon: 'none'
})
} finally {
this.saving = false
}
}
}
}
</script>
<style scoped>
.container {
background-color: #f5f5f5;
min-height: 100vh;
}
.page-header {
background: white;
padding: 30rpx;
text-align: center;
border-bottom: 1rpx solid #eee;
}
.page-title {
font-size: 36rpx;
font-weight: bold;
color: #333;
}
.form-container {
padding: 20rpx;
}
.form-section {
background: white;
border-radius: 20rpx;
margin-bottom: 20rpx;
overflow: hidden;
}
.section-title {
padding: 30rpx;
font-size: 30rpx;
font-weight: bold;
color: #333;
border-bottom: 1rpx solid #f5f5f5;
}
.form-item {
display: flex;
align-items: center;
padding: 30rpx;
border-bottom: 1rpx solid #f5f5f5;
}
.form-item.no-border {
border-bottom: none;
}
.form-label {
width: 200rpx;
font-size: 28rpx;
color: #333;
flex-shrink: 0;
}
.form-input {
flex: 1;
font-size: 28rpx;
color: #333;
margin-left: 20rpx;
}
.form-textarea {
flex: 1;
font-size: 28rpx;
color: #333;
margin-left: 20rpx;
min-height: 100rpx;
}
.region-picker {
flex: 1;
display: flex;
align-items: center;
justify-content: space-between;
margin-left: 20rpx;
padding: 20rpx 0;
}
.region-container {
flex: 1;
margin-left: 20rpx;
}
.region-text {
font-size: 28rpx;
color: #333;
}
.region-placeholder {
font-size: 28rpx;
color: #999;
}
.save-section {
padding: 40rpx 20rpx;
}
.save-btn {
width: 100%;
height: 90rpx;
background: linear-gradient(135deg, #FF4444 0%, #FF6666 100%);
border: none;
border-radius: 45rpx;
color: white;
font-size: 32rpx;
font-weight: bold;
display: flex;
align-items: center;
justify-content: center;
}
.save-btn:disabled {
background: #ccc;
}
</style>
+482
View File
@@ -0,0 +1,482 @@
<template>
<view class="container">
<!-- 顶部搜索框 -->
<view class="search-container">
<view class="search-box">
<uni-icons type="search" size="16" color="#999"></uni-icons>
<input class="search-input" placeholder="请输入关键词搜索" />
</view>
</view>
<!-- 轮播图 -->
<view class="banner-container" v-if="banners.length > 0">
<swiper class="banner-swiper" indicator-dots="true" autoplay="true" interval="3000" duration="500">
<swiper-item v-for="banner in banners" :key="banner.id" @click="onBannerClick(banner)">
<view class="banner-item">
<image class="banner-image" :src="getFullImageUrl(banner.image_url)" mode="aspectFill"></image>
<!-- <view class="banner-content" v-if="banner.title || banner.description">
<text class="banner-title" v-if="banner.title">{{ banner.title }}</text>
<text class="banner-description" v-if="banner.description">{{ banner.description }}</text>
</view> -->
</view>
</swiper-item>
</swiper>
</view>
<!-- 分类导航 -->
<view class="category-container" v-if="categories.length > 0">
<swiper class="category-swiper" indicator-dots="true" v-if="categoryPages.length > 1">
<swiper-item v-for="(page, pageIndex) in categoryPages" :key="pageIndex">
<view class="category-grid">
<view class="category-row" v-for="(row, rowIndex) in page" :key="rowIndex">
<view class="category-item" v-for="category in row" :key="category.id" @click="navigateToCategory(category.id)">
<image v-if="category.category_icon" class="category-icon" :src="getFullImageUrl(category.category_icon)" mode="aspectFit"></image>
<uni-icons v-else type="apps" size="40" color="#FF4444"></uni-icons>
<text class="category-text">{{ category.category_name }}</text>
</view>
</view>
</view>
</swiper-item>
</swiper>
<!-- 如果只有一页分类,不显示swiper -->
<view class="category-grid" v-else-if="categoryPages.length === 1">
<view class="category-row" v-for="(row, rowIndex) in categoryPages[0]" :key="rowIndex">
<view class="category-item" v-for="category in row" :key="category.id" @click="navigateToCategory(category.id)">
<image v-if="category.category_icon" class="category-icon" :src="getFullImageUrl(category.category_icon)" mode="aspectFit"></image>
<uni-icons v-else type="apps" size="40" color="#FF4444"></uni-icons>
<text class="category-text">{{ category.category_name }}</text>
</view>
</view>
</view>
</view>
<!-- 一级商品列表 -->
<view class="product-section" v-if="primaryProducts.length > 0">
<view class="section-header">
<text class="section-title">热门商品</text>
<text class="view-all" @click="viewAllProducts">查看全部></text>
</view>
<view class="product-grid">
<view class="product-item" v-for="product in displayProducts" :key="product.id" @click="navigateToProduct(product.id)">
<view class="product-image-container">
<image v-if="product.product_images"
:src="getFullImageUrl(getFirstImage(product.product_images))"
mode="aspectFill"
class="product-image"></image>
<view v-else class="default-image">
<uni-icons type="image" size="60" color="#ccc"></uni-icons>
</view>
</view>
<view class="product-info">
<text class="product-name">{{ product.product_name }}</text>
<text class="product-description">{{ product.product_description }}</text>
<view class="product-price">
<text class="current-price">¥{{ product.current_price }}</text>
<text class="original-price" v-if="product.original_price > product.current_price">¥{{ product.original_price }}</text>
</view>
<view class="product-stats">
<text class="stats-text">销量 {{ product.sales_count }}</text>
<text class="stats-text">库存 {{ product.stock_quantity }}</text>
<!-- <text class="stats-text">浏览 {{ product.view_count }}</text> -->
</view>
</view>
</view>
</view>
</view>
</view>
</template>
<script>
import request from '@/utils/request.js'
export default {
data() {
return {
banners: [],
categories: [],
primaryProducts: [],
token: ''
}
},
onLoad() {
this.checkLogin()
this.loadData()
},
computed: {
// 将分类按每页8个分组,用于滑动分页
categoryPages() {
const pages = []
for (let i = 0; i < this.categories.length; i += 8) {
const pageCategories = this.categories.slice(i, i + 8)
// 每页内部按每行4个分组
const rows = []
for (let j = 0; j < pageCategories.length; j += 4) {
rows.push(pageCategories.slice(j, j + 4))
}
pages.push(rows)
}
return pages
},
// 首页只显示前8个商品,每行2个
displayProducts() {
return this.primaryProducts
}
},
methods: {
// 检查登录状态
checkLogin() {
this. token = uni.getStorageSync('token')
if (!this. token) {
uni.redirectTo({
url: '/pages/login/login'
})
}
},
// 加载数据
async loadData() {
try {
// 加载首页数据
const res = await request.get('/back/user/home/data')
if (res.success) {
this.banners = res.data.banners || []
this.categories = res.data.categories || []
this.primaryProducts = res.data.primary_products || []
this.primaryProducts=this.primaryProducts.slice(0,12)
}
} catch (error) {
console.error('加载首页数据失败:', error)
// uni.showToast({
// title: '加载数据失败',
// icon: 'none'
// })
}
},
// 获取完整的图片URL
getFullImageUrl(url) {
return request.getImageUrl(url)
},
// 获取商品的第一张图片
getFirstImage(images) {
if (!images) return ''
// 如果是逗号分隔的字符串
if (typeof images === 'string') {
return images.split(',')[0].trim()
}
// 如果是数组
if (Array.isArray(images) && images.length > 0) {
return images[0]
}
return ''
},
// 导航到分类页面(商城页面)
navigateToCategory(categoryId) {
uni.setStorage({
data:categoryId,
key:"categoryId",
success() {
setTimeout(()=>{
uni.switchTab({
url: `/pages/mall/mall`
})
},500)
}
})
},
// 导航到商品详情
navigateToProduct(productId) {
uni.navigateTo({
url: `/pages/product/detail?id=${productId}&type=primary`
})
},
// 轮播图点击事件
onBannerClick(banner) {
if (banner.link_url) {
// 如果有链接,跳转到对应页面
if (banner.link_url.startsWith('http')) {
// 外部链接,打开浏览器
// #ifdef APP-PLUS
plus.runtime.openURL(banner.link_url)
// #endif
// #ifdef H5
window.open(banner.link_url, '_blank')
// #endif
} else {
// 内部链接,使用uni.navigateTo
uni.navigateTo({
url: banner.link_url
})
}
}
},
// 查看全部商品
async viewAllProducts() {
try {
// 加载首页数据
const res = await request.get('/back/user/home/data')
if (res.success) {
this.banners = res.data.banners || []
this.categories = res.data.categories || []
this.primaryProducts = res.data.primary_products || []
}
} catch (error) {
console.error('加载首页数据失败:', error)
// uni.showToast({
// title: '加载数据失败',
// icon: 'none'
// })
}
}
}
}
</script>
<style scoped>
.container {
background-color: #f5f5f5;
min-height: 100vh;
}
/* 搜索框样式 */
.search-container {
background: linear-gradient(135deg, #FF4444 0%, #FF6666 100%);
padding: 20rpx;
}
.search-box {
background-color: #fff;
border-radius: 50rpx;
padding: 20rpx 30rpx;
display: flex;
align-items: center;
}
.search-box uni-icons {
margin-right: 20rpx;
}
.search-input {
flex: 1;
font-size: 28rpx;
color: #999;
}
/* 轮播图样式 */
.banner-container {
margin: 20rpx;
border-radius: 16rpx;
overflow: hidden;
box-shadow: 0 4rpx 12rpx rgba(0,0,0,0.1);
}
.banner-swiper {
height: 300rpx;
}
.banner-item {
position: relative;
height: 100%;
}
.banner-image {
width: 100%;
height: 100%;
}
.banner-content {
position: absolute;
right: 30rpx;
top: 30rpx;
color: #333;
}
.banner-title {
display: block;
font-size: 32rpx;
font-weight: bold;
margin-bottom: 10rpx;
color: #fff;
text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
}
.banner-description {
display: block;
font-size: 24rpx;
color: #fff;
text-shadow: 1px 1px 2px rgba(0,0,0,0.5);
}
/* 分类容器样式 */
.category-container {
margin: 20rpx;
background-color: #fff;
border-radius: 16rpx;
overflow: hidden;
}
.category-swiper {
height: 400rpx;
}
/* 分类网格样式 */
.category-grid {
padding: 40rpx 20rpx;
}
.category-row {
display: flex;
justify-content: space-between;
margin-bottom: 40rpx;
}
.category-row:last-child {
margin-bottom: 0;
}
.category-item {
display: flex;
flex-direction: column;
align-items: center;
width: 140rpx;
}
.category-item uni-icons {
margin-bottom: 20rpx;
}
.category-icon {
width: 80rpx;
height: 80rpx;
margin-bottom: 20rpx;
}
.category-text {
font-size: 24rpx;
color: #333;
}
/* 商品区域样式 */
.product-section {
margin: 20rpx;
background-color: #fff;
border-radius: 16rpx;
padding: 30rpx;
}
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30rpx;
}
.section-title {
font-size: 32rpx;
font-weight: bold;
color: #333;
}
.view-all {
font-size: 24rpx;
color: #999;
}
/* 商品网格样式 */
.product-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20rpx;
}
.product-item {
background-color: #f8f8f8;
border-radius: 12rpx;
overflow: hidden;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}
.product-image-container {
width: 100%;
height: 200rpx;
position: relative;
}
.product-image {
width: 100%;
height: 100%;
}
.default-image {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background-color: #f0f0f0;
}
.product-info {
padding: 20rpx;
}
.product-name {
display: block;
font-size: 28rpx;
font-weight: bold;
color: #333;
margin-bottom: 10rpx;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.product-description {
display: block;
font-size: 24rpx;
color: #666;
margin-bottom: 15rpx;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.product-price {
display: flex;
align-items: center;
margin-bottom: 10rpx;
}
.current-price {
font-size: 32rpx;
font-weight: bold;
color: #FF4444;
margin-right: 15rpx;
}
.original-price {
font-size: 24rpx;
color: #999;
text-decoration: line-through;
}
.product-stats {
display: flex;
justify-content: space-between;
}
.stats-text {
font-size: 22rpx;
color: #999;
}
</style>
+251
View File
@@ -0,0 +1,251 @@
<template>
<view class="container">
<view class="login-header">
<text class="app-title">商帮帮</text>
<!-- <text class="app-subtitle">虚拟商品交易平台</text> -->
</view>
<view class="login-form">
<view class="form-item">
<uni-icons type="phone" size="20" color="rgba(255,255,255,0.8)"></uni-icons>
<input class="form-input"
v-model="loginForm.phone"
type="number"
placeholder="请输入手机号"
maxlength="11" />
</view>
<view class="form-item">
<uni-icons type="locked" size="20" color="rgba(255,255,255,0.8)"></uni-icons>
<input class="form-input"
v-model="loginForm.password"
type="password"
placeholder="请输入密码" />
</view>
<button class="login-btn" @click="handleLogin" :disabled="loginLoading">
{{ loginLoading ? '登录中...' : '登录' }}
</button>
<view class="action-links">
<text class="link-text" @click="goToRegister">立即注册</text>
<!-- <text class="link-text" @click="forgotPassword">忘记密码</text> -->
</view>
</view>
</view>
</template>
<script>
import request from '@/utils/request.js'
export default {
data() {
return {
loginForm: {
phone: '',
password: ''
},
loginLoading: false
}
},
onLoad() {
// 检查是否已登录
const token = uni.getStorageSync('token')
if (token) {
uni.reLaunch({
url: '/pages/index/index'
})
}
},
methods: {
// 登录验证
validateForm() {
if (!this.loginForm.phone) {
uni.showToast({
title: '请输入手机号',
icon: 'none'
})
return false
}
if (!/^1[3-9]\d{9}$/.test(this.loginForm.phone)) {
uni.showToast({
title: '手机号格式不正确',
icon: 'none'
})
return false
}
if (!this.loginForm.password) {
uni.showToast({
title: '请输入密码',
icon: 'none'
})
return false
}
if (this.loginForm.password.length < 6) {
uni.showToast({
title: '密码长度不能少于6位',
icon: 'none'
})
return false
}
return true
},
// 处理登录
async handleLogin() {
if (!this.validateForm()) {
return
}
this.loginLoading = true
try {
const res = await request.post('/back/auth/login', this.loginForm)
if (res.success) {
const { token, user } = res.data
// 保存token和用户信息到本地存储
uni.setStorageSync('token', token)
uni.setStorageSync('userInfo', user)
uni.showToast({
title: '登录成功',
icon: 'success'
})
// 跳转到首页
setTimeout(() => {
uni.reLaunch({
url: '/pages/index/index'
})
}, 1500)
} else {
uni.showToast({
title: res.message || '登录失败',
icon: 'none'
})
}
} catch (error) {
// console.error('登录失败:', error)
// uni.showToast({
// title: '网络错误,请稍后重试',
// icon: 'none'
// })
} finally {
this.loginLoading = false
}
},
// 跳转到注册页面
goToRegister() {
uni.navigateTo({
url: '/pages/register/register'
})
},
// 忘记密码
forgotPassword() {
uni.showModal({
title: '忘记密码',
content: '请联系客服重置密码\n客服电话:400-123-4567',
showCancel: false
})
}
}
}
</script>
<style scoped>
.container {
background: linear-gradient(135deg, #FF4444 0%, #FF6666 100%);
min-height: 100vh;
padding: 100rpx 60rpx;
display: flex;
flex-direction: column;
}
.login-header {
text-align: center;
margin-bottom: 120rpx;
color: #fff;
}
.app-title {
display: block;
font-size: 64rpx;
font-weight: bold;
margin-bottom: 20rpx;
}
.app-subtitle {
font-size: 28rpx;
opacity: 0.9;
}
.login-form {
flex: 1;
}
.form-item {
background-color: rgba(255,255,255,0.1);
border-radius: 50rpx;
display: flex;
align-items: center;
padding: 0 40rpx;
margin-bottom: 40rpx;
border: 2rpx solid rgba(255,255,255,0.2);
}
.form-item:focus-within {
background-color: rgba(255,255,255,0.2);
border-color: rgba(255,255,255,0.5);
}
.form-item uni-icons {
margin-right: 30rpx;
}
.form-input {
flex: 1;
height: 100rpx;
font-size: 32rpx;
color: #fff;
}
.form-input::placeholder {
color: rgba(255,255,255,0.7);
}
.login-btn {
background-color: rgba(255,255,255,0.9);
color: #FF4444;
border-radius: 50rpx;
height: 100rpx;
font-size: 36rpx;
font-weight: bold;
margin: 60rpx 0;
border: none;
}
.login-btn:disabled {
background-color: rgba(255,255,255,0.5);
color: rgba(255,68,68,0.5);
}
.action-links {
display: flex;
justify-content: space-between;
padding: 0 20rpx;
}
.link-text {
color: rgba(255,255,255,0.9);
font-size: 28rpx;
text-decoration: underline;
}
</style>
+753
View File
@@ -0,0 +1,753 @@
<template>
<view class="container">
<!-- 筛选栏 -->
<view class="filter-bar">
<view class="filter-item" @click="showSortMenu('default')">
<text class="filter-text" :class="{ active: sortType === 'default' }">默认</text>
<uni-icons type="arrowdown" size="12" color="#999"></uni-icons>
</view>
<view class="filter-item" @click="showSortMenu('price')">
<text class="filter-text" :class="{ active: sortType === 'price' }">价格</text>
<uni-icons type="arrowdown" size="12" color="#999"></uni-icons>
</view>
<view class="filter-item" @click="showSortMenu('quantity')">
<text class="filter-text" :class="{ active: sortType === 'quantity' }">库存</text>
<uni-icons type="arrowdown" size="12" color="#999"></uni-icons>
</view>
<view class="filter-item" @click="showAddressFilter">
<text class="filter-text" :class="{ active: selectedRegion }">{{ selectedRegion || '地区' }}</text>
<uni-icons type="location" size="12" color="#999"></uni-icons>
</view>
<view class="filter-item" @click="resetAllFilters">
<text class="filter-text">重置</text>
<uni-icons type="reload" size="12" color="#999"></uni-icons>
</view>
<view class="filter-item" @click="showFilterPanel">
<uni-icons type="bars" size="16" color="#999"></uni-icons>
</view>
</view>
<!-- 商品列表 -->
<view class="product-list">
<view class="product-item"
:class="{ 'disabled': !item.can_purchase }"
v-for="(item, index) in productList"
:key="index"
@click="goToDetail(item)">
<view class="product-image-container">
<image v-if="item.product_images"
:src="getFullImageUrl(getFirstImage(item.product_images))"
mode="aspectFill"
:class="['product-image', { 'image-disabled': !item.can_purchase }]"></image>
<view v-else class="default-image">
<uni-icons type="image" size="40" color="#ccc"></uni-icons>
</view>
<!-- 购买限制提示遮罩 -->
<view class="purchase-limit-overlay" v-if="!item.can_purchase">
<!-- <text class="limit-text">{{ item.purchase_limit_message || '暂时无法购买' }}</text> -->
</view>
</view>
<view class="product-info">
<text class="product-title" :class="{ 'text-disabled': !item.can_purchase }">{{ item.product_name }}</text>
<view class="product-stats">
<text class="stats-text">销量 {{ item.sales_count || 0 }}</text>
<text class="stats-text">库存 {{ item.quantity || 0 }}</text>
</view>
<view class="product-price">
<text class="current-price" :class="{ 'price-disabled': !item.can_purchase }">¥{{ item.selling_price || item.current_price }}</text>
</view>
<view class="seller-info" v-if="item.seller">
<text class="seller-text" :class="{ 'text-disabled': !item.can_purchase }">卖家:{{ item.seller.real_name || item.seller.phone }}</text>
</view>
</view>
</view>
</view>
<!-- 加载更多 -->
<view class="load-more" v-if="hasMore">
<text>加载更多...</text>
</view>
<view class="no-more" v-else-if="productList.length > 0">
<text>没有更多了</text>
</view>
<!-- 地址筛选弹窗 -->
<view class="address-modal" v-if="showAddressModal" @tap="hideAddressFilter">
<view class="modal-content" @tap.stop>
<view class="modal-header">
<text class="modal-title">选择地区</text>
<text class="modal-close" @tap="hideAddressFilter">×</text>
</view>
<view class="modal-body">
<view class="region-options">
<!-- <view class="region-option" :class="{ active: !tempProvince }" @tap="selectAllRegion">
<text class="option-text">全部地区</text>
<view class="option-check" v-if="!tempProvince">✓</view>
</view> -->
<!-- 使用k-region组件 -->
<view class="k-region-container">
<Region
:width="300"
:height="92"
:showAllDistrict="true"
:isRevise="false"
@region="onRegionChange"
/>
</view>
</view>
<view class="filter-actions">
<button class="reset-btn" @tap="resetRegionFilter">重置</button>
<button class="confirm-btn" @tap="confirmRegionFilter">确定</button>
</view>
</view>
</view>
</view>
</view>
</template>
<script>
import request from '@/utils/request.js'
import Region from '@/components/k-region.vue'
export default {
components: {
Region
},
data() {
return {
productList: [],
sortType: 'default',
currentPage: 1,
pageSize: 10,
hasMore: true,
loading: false,
categoryId: '',
// 地址筛选相关
showAddressModal: false,
selectedProvince: '',
selectedCity: '',
selectedDistrict: '',
tempProvince: '',
tempCity: '',
tempDistrict: '',
showAllDistrict: false
}
},
onPullDownRefresh() {
var that=this
uni.getStorage({
key:"categoryId",
success(res) {
that.categoryId=res.data
that.currentPage=1
that.loadProducts()
uni.setStorage({
key:"categoryId",
data:0,
success() {
}
})
},
fail() {
that.loadProducts()
}
})
},
computed: {
selectedRegion() {
if (this.selectedProvince && this.selectedCity) {
if (this.selectedDistrict) {
return `${this.selectedProvince} ${this.selectedCity} ${this.selectedDistrict}`
} else {
return `${this.selectedProvince} ${this.selectedCity} 全部区`
}
}
return ''
},
regionText() {
if (this.tempProvince && this.tempCity) {
if (this.tempDistrict) {
return `${this.tempProvince} ${this.tempCity} ${this.tempDistrict}`
} else if (this.showAllDistrict) {
return `${this.tempProvince} ${this.tempCity} 全部区`
} else {
return `${this.tempProvince} ${this.tempCity}`
}
}
return ''
}
},
onShow() {
const token = uni.getStorageSync('token')
if (!token) {
uni.reLaunch({
url: '/pages/login/login'
})
return
}
var that=this
that.currentPage=1
uni.getStorage({
key:"categoryId",
success(res) {
that.categoryId=res.data
that.loadProducts()
uni.setStorage({
key:"categoryId",
data:0,
success() {
}
})
},
fail() {
that.loadProducts()
}
})
},
onLoad(options) {
// 检查登录状态
// // 保存分类参数
// if (options.category_id) {
// this.categoryId = options.category_id
// }
// this.loadProducts()
},
onReachBottom() {
if (this.hasMore && !this.loading) {
this.loadMore()
}
},
methods: {
// 获取完整的图片URL
getFullImageUrl(url) {
return request.getImageUrl(url)
},
// 获取商品的第一张图片
getFirstImage(images) {
if (!images) return ''
// 如果是逗号分隔的字符串
if (typeof images === 'string') {
return images.split(',')[0].trim()
}
// 如果是数组
if (Array.isArray(images) && images.length > 0) {
return images[0]
}
return ''
},
// 加载商品列表
async loadProducts() {
this.loading = true
try {
const params = {
page: this.currentPage,
page_size: this.pageSize,
sort: this.sortType
}
// 如果有分类ID,添加到参数中
if (this.categoryId) {
params.category_id = this.categoryId
}
// 如果有地址筛选,添加到参数中
if (this.selectedProvince) {
params.province = this.selectedProvince
}
if (this.selectedCity) {
params.city = this.selectedCity
}
if (this.selectedDistrict) {
params.district = this.selectedDistrict
}
// 这里显示二级商品(用户挂售的商品)
const res = await request.get('/back/user/products/secondary', params)
if (res.success) {
const data = res.data
if (this.currentPage === 1) {
this.productList = data.list || []
} else {
this.productList = [...this.productList, ...(data.list || [])]
}
this.hasMore = this.productList.length < data.total
}
} catch (error) {
console.error('加载商品失败:', error)
uni.showToast({
title: '加载失败',
icon: 'none'
})
} finally {
this.loading = false
}
},
// 加载更多
loadMore() {
this.currentPage++
this.loadProducts()
},
// 显示排序菜单
showSortMenu(type) {
this.sortType = type
this.currentPage = 1
this.loadProducts()
},
// 显示筛选面板
showFilterPanel() {
uni.showActionSheet({
itemList: ['价格升序', '价格降序', '销量排序', '库存排序'],
success: (res) => {
const sortTypes = ['price_asc', 'price_desc', 'sales', 'quantity']
this.sortType = sortTypes[res.tapIndex]
this.currentPage = 1
this.loadProducts()
}
})
},
// 跳转到商品详情
goToDetail(item) {
// 如果不可购买,显示提示
if (!item.can_purchase) {
uni.showToast({
title: item.purchase_limit_message || '暂时无法购买',
icon: 'none',
duration: 2000
})
return
}
uni.navigateTo({
url: `/pages/product/detail?id=${item.id}&type=secondary`
})
},
// 显示地址筛选
showAddressFilter() {
this.showAddressModal = true
// 将当前选择的地址设为临时变量
this.tempProvince = this.selectedProvince
this.tempCity = this.selectedCity
this.tempDistrict = this.selectedDistrict
// 如果选择了省市但没有选择区,说明是"全部区"状态
this.showAllDistrict = this.selectedProvince && this.selectedCity && !this.selectedDistrict
},
// 隐藏地址筛选
hideAddressFilter() {
this.showAddressModal = false
},
// k-region组件回调
onRegionChange(regionArray) {
console.log('选择的地区:', regionArray)
this.tempProvince = regionArray[0] || ''
this.tempCity = regionArray[1] || ''
this.tempDistrict = regionArray[2] || ''
// 如果选择了省市但区为空,说明选择了"全部区"
this.showAllDistrict = this.tempProvince && this.tempCity && !this.tempDistrict
},
// 重置地区筛选
resetRegionFilter() {
this.tempProvince = ''
this.tempCity = ''
this.tempDistrict = ''
this.showAllDistrict = false
this.selectedProvince = ''
this.selectedCity = ''
this.selectedDistrict = ''
this.currentPage = 1
this.loadProducts()
this.hideAddressFilter()
},
// 确认地区筛选
confirmRegionFilter() {
this.selectedProvince = this.tempProvince
this.selectedCity = this.tempCity
// 如果选择了"全部区",则不设置具体区名
this.selectedDistrict = this.showAllDistrict ? '' : this.tempDistrict
this.currentPage = 1
this.loadProducts()
this.hideAddressFilter()
},
// 选择全部地区
selectAllRegion() {
this.tempProvince = ''
this.tempCity = ''
this.tempDistrict = ''
this.showAllDistrict = false
},
// 选择全部区
selectAllDistrict() {
this.tempDistrict = ''
this.showAllDistrict = true
},
// 重置所有筛选条件
resetAllFilters() {
uni.showModal({
title: '提示',
content: '确定要重置所有筛选条件吗?',
success: (res) => {
if (res.confirm) {
// 重置排序
this.sortType = 'default'
// 重置地区筛选
this.selectedProvince = ''
this.selectedCity = ''
this.selectedDistrict = ''
this.tempProvince = ''
this.tempCity = ''
this.tempDistrict = ''
this.showAllDistrict = false
// 重置分类
this.categoryId = ''
// 重置分页
this.currentPage = 1
// 重新加载数据
this.loadProducts()
uni.showToast({
title: '已重置',
icon: 'success'
})
}
}
})
}
}
}
</script>
<style scoped>
.container {
background-color: #f5f5f5;
min-height: 100vh;
}
/* 筛选栏样式 */
.filter-bar {
background-color: #fff;
display: flex;
padding: 20rpx 30rpx;
border-bottom: 1rpx solid #eee;
}
.filter-item {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
}
.filter-text {
font-size: 28rpx;
color: #333;
margin-right: 10rpx;
}
.filter-text.active {
color: #FF4444;
}
/* 商品列表样式 */
.product-list {
padding: 20rpx;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.product-item {
background-color: #fff;
border-radius: 12rpx;
margin-bottom: 20rpx;
overflow: hidden;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
width: 48%;
}
.product-item.disabled {
opacity: 0.6;
background-color: #f5f5f5;
}
.product-image-container {
width: 100%;
height: 200rpx;
position: relative;
}
.product-image {
width: 100%;
height: 100%;
}
.product-image.image-disabled {
filter: grayscale(100%);
opacity: 0.5;
}
.purchase-limit-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 10;
}
.limit-text {
color: #fff;
font-size: 24rpx;
text-align: center;
padding: 10rpx 20rpx;
background-color: rgba(0, 0, 0, 0.6);
border-radius: 8rpx;
}
.default-image {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background-color: #f0f0f0;
}
.product-info {
padding: 20rpx;
}
.product-title {
display: block;
font-size: 26rpx;
font-weight: bold;
color: #333;
margin-bottom: 8rpx;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.product-title.text-disabled {
color: #999;
}
.product-stats {
display: flex;
margin-bottom: 10rpx;
justify-content: space-between;
}
.stats-text {
font-size: 20rpx;
color: #999;
}
.product-price {
display: flex;
align-items: center;
margin-bottom: 8rpx;
}
.current-price {
font-size: 28rpx;
font-weight: bold;
color: #FF4444;
}
.current-price.price-disabled {
color: #999;
}
.original-price {
font-size: 20rpx;
color: #999;
text-decoration: line-through;
margin-left: 10rpx;
}
.seller-info {
margin-top: 8rpx;
padding-top: 8rpx;
border-top: 1rpx solid #f0f0f0;
}
.seller-text {
font-size: 20rpx;
color: #666;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.seller-text.text-disabled {
color: #999;
}
/* 加载更多样式 */
.load-more, .no-more {
text-align: center;
padding: 40rpx;
color: #999;
font-size: 24rpx;
}
/* 地址筛选弹窗样式 */
.address-modal {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
z-index: 999;
display: flex;
align-items: center;
justify-content: center;
}
.modal-content {
background-color: #fff;
border-radius: 20rpx;
width: 600rpx;
max-height: 80vh;
overflow: hidden;
}
.modal-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 30rpx;
border-bottom: 1rpx solid #eee;
}
.modal-title {
font-size: 32rpx;
font-weight: bold;
color: #333;
}
.modal-close {
font-size: 40rpx;
color: #999;
width: 40rpx;
height: 40rpx;
display: flex;
align-items: center;
justify-content: center;
}
.modal-body {
padding: 30rpx;
}
.region-options {
margin-bottom: 30rpx;
}
.region-option {
display: flex;
align-items: center;
justify-content: space-between;
padding: 30rpx 20rpx;
background-color: #f8f8f8;
border-radius: 12rpx;
margin-bottom: 20rpx;
}
.region-option.active {
background-color: #e3f2fd;
border: 2rpx solid #2196f3;
}
.option-text {
font-size: 28rpx;
color: #333;
}
.option-check {
font-size: 28rpx;
color: #2196f3;
font-weight: bold;
}
.region-picker {
display: flex;
align-items: center;
justify-content: space-between;
padding: 30rpx 20rpx;
background-color: #f8f8f8;
border-radius: 12rpx;
}
.k-region-container {
background-color: #f8f8f8;
border-radius: 12rpx;
padding: 20rpx;
margin-bottom: 20rpx;
}
.region-text {
font-size: 28rpx;
color: #333;
}
.region-placeholder {
font-size: 28rpx;
color: #999;
}
.filter-actions {
display: flex;
gap: 20rpx;
}
.reset-btn, .confirm-btn {
flex: 1;
height: 80rpx;
border-radius: 40rpx;
font-size: 28rpx;
border: none;
display: flex;
align-items: center;
justify-content: center;
}
.reset-btn {
background-color: #f5f5f5;
color: #666;
}
.confirm-btn {
background: linear-gradient(135deg, #FF4444 0%, #FF6666 100%);
color: #fff;
}
</style>
+837
View File
@@ -0,0 +1,837 @@
<template>
<view class="container">
<!-- 订单状态 -->
<view class="status-section">
<view class="status-icon" :class="statusClass">
<uni-icons :type="statusIcon" size="40" color="#fff"></uni-icons>
</view>
<view class="status-info">
<text class="status-text">{{ statusText }}</text>
<text class="status-desc">{{ statusDesc }}</text>
</view>
</view>
<!-- 订单信息 -->
<view class="order-section">
<view class="section-title">订单信息</view>
<view class="order-item">
<text class="item-label">订单号:</text>
<text class="item-value">{{ orderInfo.order_no }}</text>
</view>
<view class="order-item">
<text class="item-label">订单类型:</text>
<text class="item-value">{{ orderInfo.product_type === 1 ? '一级商品' : '二级商品' }}</text>
</view>
<view class="order-item">
<text class="item-label">下单时间:</text>
<text class="item-value">{{ formatTime(orderInfo.created_at) }}</text>
</view>
<view class="order-item" v-if="orderInfo.confirm_time">
<text class="item-label">确认时间:</text>
<text class="item-value">{{ formatTime(orderInfo.confirm_time) }}</text>
</view>
<view class="order-item" v-if="orderInfo.complete_time">
<text class="item-label">完成时间:</text>
<text class="item-value">{{ formatTime(orderInfo.complete_time) }}</text>
</view>
</view>
<!-- 商品信息 -->
<view class="product-section">
<view class="section-title">商品信息</view>
<view class="product-card">
<image v-if="productImage" :src="getFullImageUrl(productImage)" class="product-image" mode="aspectFill"></image>
<view class="default-image" v-else>
<uni-icons type="image" size="40" color="#ccc"></uni-icons>
</view>
<view class="product-info">
<text class="product-name">{{ orderInfo.product_name }}</text>
<view class="product-price">
<text class="price-label">单价:</text>
<text class="price-value">¥{{ orderInfo.unit_price||orderInfo.selling_price }}</text>
</view>
<view class="product-price">
<text class="price-label">订单金额:</text>
<text class="price-value">¥{{ orderInfo.total_amount }}</text>
</view>
<view class="product-quantity">
<text class="quantity-label">数量:</text>
<text class="quantity-value">{{ orderInfo.quantity || 1 }}</text>
</view>
</view>
</view>
</view>
<!-- 交易双方信息 -->
<view class="parties-section">
<view class="section-title">交易信息</view>
<view class="party-info" v-if="orderType === 'purchase'">
<text class="party-label">卖家:</text>
<text class="party-value">{{ orderInfo.seller ? ( orderInfo.seller.real_name||orderInfo.seller.customer_name || orderInfo.seller.phone) : '暂无' }}</text>
</view>
<view class="party-info" v-if="orderType === 'sales'">
<text class="party-label">买家:</text>
<text class="party-value">{{ orderInfo.buyer ? (orderInfo.buyer.real_name || orderInfo.buyer.customer_name || orderInfo.buyer.phone) : '暂无' }}</text>
</view>
<view class="party-info" v-if="orderInfo.address">
<text class="party-label">收货地址:</text>
<text class="party-value">{{ formatAddress(orderInfo.address) }}</text>
</view>
</view>
<!-- 付款凭证 -->
<view class="proof-section" v-if="orderInfo.payment_proof_image">
<view class="section-title">付款凭证</view>
<view class="proof-image" @click="previewProof">
<image :src="getFullImageUrl(orderInfo.payment_proof_image)" mode="aspectFill"></image>
<view class="proof-overlay">
<uni-icons type="eye" size="30" color="#fff"></uni-icons>
<text class="proof-text">点击查看</text>
</view>
</view>
</view>
<!-- 留言区域 -->
<view class="message-section">
<view class="section-title">
<text>订单留言</text>
<text class="message-count">({{ messages.length }}条)</text>
</view>
<!-- 留言列表 -->
<view class="message-list" v-if="messages.length > 0">
<view class="message-item" v-for="(msg, index) in messages" :key="index">
<view class="message-header">
<text class="message-user">{{ msg.user.real_name || '匿名用户' }}</text>
<text class="message-time">{{ formatTime(msg.created_at) }}</text>
</view>
<view class="message-content">{{ msg.content }}</view>
<!-- 留言图片 -->
<view class="message-images" v-if="msg.images">
<image
v-for="(image, imgIndex) in getMessageImages(msg.images)"
:key="imgIndex"
:src="getFullImageUrl(image)"
class="message-image"
mode="aspectFill"
@click="previewMessageImage(msg.images, imgIndex)"
/>
</view>
</view>
</view>
<view class="no-message" v-else>
<uni-icons type="chatboxes" size="40" color="#ccc"></uni-icons>
<text>暂无留言</text>
</view>
<!-- 发送留言 -->
<view class="send-message">
<view class="message-input-container">
<textarea
v-model="newMessage"
class="message-input"
placeholder="请输入留言内容..."
maxlength="500"
auto-height
></textarea>
<text class="char-count">{{ newMessage.length }}/500</text>
</view>
<!-- 图片选择和预览 -->
<view class="image-section" v-if="selectedImages.length > 0">
<view class="selected-images">
<view class="image-item" v-for="(image, index) in selectedImages" :key="index">
<image :src="image" class="selected-image" mode="aspectFill" />
<view class="remove-image" @click="removeImage(index)">
<uni-icons type="closeempty" size="16" color="#fff"></uni-icons>
</view>
</view>
</view>
</view>
<view class="send-actions">
<view class="action-buttons">
<button class="image-btn" @click="chooseImage" :disabled="selectedImages.length >= 6">
<uni-icons type="camera" size="20" color="#666"></uni-icons>
<text class="btn-text">图片({{ selectedImages.length }}/6)</text>
</button>
</view>
<button class="send-btn" @click="sendMessage" :disabled="(!newMessage.trim() && selectedImages.length === 0) || sending">
<text v-if="sending">发送中...</text>
<text v-else>发送</text>
</button>
</view>
</view>
</view>
</view>
</template>
<script>
import request from '@/utils/request.js'
export default {
data() {
return {
orderType: 'purchase', // purchase: 买单, sales: 卖单
orderId: '',
orderInfo: {},
messages: [],
newMessage: '',
selectedImages: [], // 选中的图片列表
sending: false,
loading: true
}
},
computed: {
statusClass() {
const statusMap = {
0: 'status-pending', // 待付款
1: 'status-paid', // 已付款
2: 'status-completed', // 已完成
3: 'status-cancelled' // 已取消
}
return statusMap[this.orderInfo.order_status] || 'status-pending'
},
statusIcon() {
const iconMap = {
0: 'wallet', // 待付款
1: 'checkmarkempty', // 已付款
2: 'checkbox', // 已完成
3: 'closeempty' // 已取消
}
return iconMap[this.orderInfo.order_status] || 'wallet'
},
statusText() {
const textMap = {
0: '待付款',
1: '已付款',
2: '已完成',
3: '已取消'
}
return textMap[this.orderInfo.order_status] || '未知状态'
},
statusDesc() {
const descMap = {
0: '请及时完成付款',
1: '等待卖家确认',
2: '交易已完成',
3: '订单已取消'
}
return descMap[this.orderInfo.order_status] || ''
},
productImage() {
if (this.orderInfo.product_images) {
const images = this.orderInfo.product_images
if (typeof images === 'string') {
return images.split(',')[0].trim()
}
if (Array.isArray(images) && images.length > 0) {
return images[0]
}
}
if (this.orderInfo.secondary_product?.primary_product?.product_images) {
const images = this.orderInfo.secondary_product.primary_product.product_images
if (typeof images === 'string') {
return images.split(',')[0].trim()
}
if (Array.isArray(images) && images.length > 0) {
return images[0]
}
}
return ''
},
productName() {
return this.orderInfo.primary_product?.product_name ||
this.orderInfo.secondary_product?.primary_product?.product_name ||
'未知商品'
},
productDesc() {
return this.orderInfo.primary_product?.product_description ||
this.orderInfo.secondary_product?.primary_product?.product_description ||
'暂无描述'
}
},
onLoad(options) {
// 检查登录状态
const token = uni.getStorageSync('token')
if (!token) {
uni.reLaunch({
url: '/pages/login/login'
})
return
}
this.orderType = options.type || 'purchase' // purchase 或 sales
this.orderId = options.id
if (!this.orderId) {
uni.showToast({
title: '订单ID不能为空',
icon: 'none'
})
setTimeout(() => {
uni.navigateBack()
}, 1500)
return
}
this.loadOrderDetail()
this.loadMessages()
},
methods: {
// 加载订单详情
async loadOrderDetail() {
this.loading = true
try {
const url = this.orderType === 'purchase'
? `/back/user/orders/purchase/${this.orderId}`
: `/back/user/orders/sales/${this.orderId}`
const res = await request.get(url)
if (res.success) {
this.orderInfo = res.data
} else {
throw new Error(res.message || '加载订单详情失败')
}
} catch (error) {
console.error('加载订单详情失败:', error)
uni.showToast({
title: '加载失败',
icon: 'none'
})
} finally {
this.loading = false
}
},
// 加载留言列表
async loadMessages() {
try {
const res = await request.get(`/back/user/orders/${this.orderId}/messages`,{type:this.orderType})
if (res.success) {
this.messages = res.data.list || []
}
} catch (error) {
console.error('加载留言失败:', error)
}
},
// 发送留言
async sendMessage() {
if (!this.newMessage.trim() && this.selectedImages.length === 0) {
uni.showToast({
title: '请输入留言内容或选择图片',
icon: 'none'
})
return
}
this.sending = true
try {
// 上传图片并获取URL
let imageUrls = []
if (this.selectedImages.length > 0) {
for (let image of this.selectedImages) {
const uploadRes = await request.upload('/back/upload', image)
if (uploadRes.success) {
imageUrls.push(uploadRes.data.url)
}
}
}
const res = await request.post(`/back/user/orders/${this.orderId}/messages`, {
content: this.newMessage.trim(),
images: imageUrls.join(',')
})
if (res.success) {
this.newMessage = ''
this.selectedImages = []
this.loadMessages() // 重新加载留言列表
uni.showToast({
title: '发送成功',
icon: 'success'
})
} else {
throw new Error(res.message || '发送失败')
}
} catch (error) {
console.error('发送留言失败:', error)
uni.showToast({
title: '发送失败',
icon: 'none'
})
} finally {
this.sending = false
}
},
// 预览付款凭证
previewProof() {
uni.previewImage({
urls: [this.getFullImageUrl(this.orderInfo.payment_proof_image)],
current: 0
})
},
// 获取完整图片URL
getFullImageUrl(url) {
return request.getImageUrl(url)
},
// 格式化时间
formatTime(time) {
if (!time) return '暂无'
const date = new Date(time)
const year = date.getFullYear()
const month = String(date.getMonth() + 1).padStart(2, '0')
const day = String(date.getDate()).padStart(2, '0')
const hours = String(date.getHours()).padStart(2, '0')
const minutes = String(date.getMinutes()).padStart(2, '0')
return `${year}-${month}-${day} ${hours}:${minutes}`
},
// 格式化地址
formatAddress(address) {
if (!address) return '暂无'
return `${address.province || ''} ${address.city || ''} ${address.district || ''} ${address.detail_address || ''}`
},
// 选择图片
chooseImage() {
const remaining = 6 - this.selectedImages.length
if (remaining <= 0) {
uni.showToast({
title: '最多只能选择6张图片',
icon: 'none'
})
return
}
uni.chooseImage({
count: remaining,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: (res) => {
this.selectedImages = this.selectedImages.concat(res.tempFilePaths)
}
})
},
// 删除图片
removeImage(index) {
this.selectedImages.splice(index, 1)
},
// 获取留言图片列表
getMessageImages(images) {
if (!images) return []
return images.split(',').filter(img => img.trim())
},
// 预览留言图片
previewMessageImage(images, currentIndex) {
const imageList = this.getMessageImages(images)
const urls = imageList.map(img => this.getFullImageUrl(img))
uni.previewImage({
urls: urls,
current: currentIndex
})
}
}
}
</script>
<style scoped>
.container {
background-color: #f5f5f5;
min-height: 100vh;
padding-bottom: 20rpx;
}
/* 状态区域 */
.status-section {
background: linear-gradient(135deg, #FF4444 0%, #FF6666 100%);
padding: 40rpx 30rpx;
display: flex;
align-items: center;
}
.status-icon {
width: 80rpx;
height: 80rpx;
border-radius: 40rpx;
background-color: rgba(255, 255, 255, 0.2);
display: flex;
align-items: center;
justify-content: center;
margin-right: 30rpx;
}
.status-info {
flex: 1;
}
.status-text {
display: block;
font-size: 36rpx;
font-weight: bold;
color: #fff;
margin-bottom: 10rpx;
}
.status-desc {
font-size: 26rpx;
color: rgba(255, 255, 255, 0.8);
}
/* 通用section样式 */
.order-section, .product-section, .parties-section, .proof-section, .message-section {
background-color: #fff;
margin: 20rpx;
border-radius: 16rpx;
padding: 30rpx;
}
.section-title {
font-size: 32rpx;
font-weight: bold;
color: #333;
margin-bottom: 30rpx;
display: flex;
align-items: center;
justify-content: space-between;
}
.message-count {
font-size: 24rpx;
color: #999;
font-weight: normal;
}
/* 订单信息 */
.order-item, .party-info {
display: flex;
align-items: center;
margin-bottom: 20rpx;
}
.order-item:last-child, .party-info:last-child {
margin-bottom: 0;
}
.item-label, .party-label {
width: 200rpx;
font-size: 28rpx;
color: #666;
flex-shrink: 0;
}
.item-value, .party-value {
flex: 1;
font-size: 28rpx;
color: #333;
}
/* 商品卡片 */
.product-card {
display: flex;
align-items: flex-start;
}
.product-image {
width: 120rpx;
height: 120rpx;
border-radius: 12rpx;
margin-right: 20rpx;
}
.default-image {
width: 120rpx;
height: 120rpx;
border-radius: 12rpx;
background-color: #f0f0f0;
display: flex;
align-items: center;
justify-content: center;
margin-right: 20rpx;
}
.product-info {
flex: 1;
}
.product-name {
display: block;
font-size: 30rpx;
font-weight: bold;
color: #333;
margin-bottom: 10rpx;
line-height: 1.4;
}
.product-desc {
display: block;
font-size: 24rpx;
color: #666;
margin-bottom: 15rpx;
line-height: 1.4;
}
.product-price, .product-quantity {
display: flex;
align-items: center;
margin-bottom: 10rpx;
}
.price-label, .quantity-label {
font-size: 26rpx;
color: #666;
margin-right: 10rpx;
}
.price-value {
font-size: 30rpx;
font-weight: bold;
color: #FF4444;
}
.quantity-value {
font-size: 26rpx;
color: #333;
}
/* 付款凭证 */
.proof-image {
position: relative;
width: 200rpx;
height: 200rpx;
border-radius: 12rpx;
overflow: hidden;
}
.proof-image image {
width: 100%;
height: 100%;
}
.proof-overlay {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.proof-text {
font-size: 24rpx;
color: #fff;
margin-top: 10rpx;
}
/* 留言区域 */
.message-list {
margin-bottom: 30rpx;
}
.message-item {
border-bottom: 1rpx solid #f0f0f0;
padding-bottom: 20rpx;
margin-bottom: 20rpx;
}
.message-item:last-child {
border-bottom: none;
margin-bottom: 0;
}
.message-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 15rpx;
}
.message-user {
font-size: 26rpx;
color: #666;
font-weight: bold;
}
.message-time {
font-size: 22rpx;
color: #999;
}
.message-content {
font-size: 28rpx;
color: #333;
line-height: 1.5;
}
.no-message {
text-align: center;
padding: 60rpx 0;
color: #999;
}
.no-message text {
display: block;
margin-top: 20rpx;
font-size: 26rpx;
}
/* 留言图片 */
.message-images {
margin-top: 15rpx;
display: flex;
flex-wrap: wrap;
gap: 10rpx;
}
.message-image {
width: 120rpx;
height: 120rpx;
border-radius: 8rpx;
}
/* 发送留言 */
.send-message {
border-top: 1rpx solid #f0f0f0;
padding-top: 30rpx;
}
.message-input-container {
position: relative;
margin-bottom: 20rpx;
}
.message-input {
width: 100%;
min-height: 120rpx;
padding: 20rpx;
border: 1rpx solid #e0e0e0;
border-radius: 12rpx;
font-size: 28rpx;
color: #333;
background-color: #f8f8f8;
}
.char-count {
position: absolute;
right: 20rpx;
bottom: 10rpx;
font-size: 22rpx;
color: #999;
}
/* 图片选择区域 */
.image-section {
margin-bottom: 20rpx;
}
.selected-images {
display: flex;
flex-wrap: wrap;
gap: 10rpx;
}
.image-item {
position: relative;
width: 100rpx;
height: 100rpx;
}
.selected-image {
width: 100%;
height: 100%;
border-radius: 8rpx;
}
.remove-image {
position: absolute;
top: -10rpx;
right: -10rpx;
width: 32rpx;
height: 32rpx;
background-color: #ff4444;
border-radius: 16rpx;
display: flex;
align-items: center;
justify-content: center;
}
/* 发送操作区域 */
.send-actions {
display: flex;
align-items: center;
gap: 20rpx;
}
.action-buttons {
flex: 1;
}
.image-btn {
background: transparent;
border: 1rpx solid #e0e0e0;
border-radius: 8rpx;
padding: 10rpx 20rpx;
display: flex;
align-items: center;
justify-content: center;
gap: 10rpx;
font-size: 24rpx;
color: #666;
}
.image-btn:disabled {
color: #ccc;
border-color: #f0f0f0;
}
.btn-text {
font-size: 24rpx;
}
.send-btn {
width: 120rpx;
height: 60rpx;
background: linear-gradient(135deg, #FF4444 0%, #FF6666 100%);
border: none;
border-radius: 30rpx;
color: #fff;
font-size: 26rpx;
font-weight: bold;
display: flex;
align-items: center;
justify-content: center;
}
.send-btn:disabled {
background: #ccc;
}
/* 状态颜色 */
.status-pending {
background-color: rgba(255, 193, 7, 0.2) !important;
}
.status-paid {
background-color: rgba(23, 162, 184, 0.2) !important;
}
.status-completed {
background-color: rgba(40, 167, 69, 0.2) !important;
}
.status-cancelled {
background-color: rgba(220, 53, 69, 0.2) !important;
}
</style>
+694
View File
@@ -0,0 +1,694 @@
<template>
<view class="container">
<!-- 状态切换标签 -->
<view class="status-tabs">
<view class="tab-item"
:class="{ active: currentStatus === 'all' }"
@click="switchStatus('all')">
<text class="tab-text">全部</text>
</view>
<view class="tab-item"
:class="{ active: currentStatus === '0' }"
@click="switchStatus('0')">
<text class="tab-text">待付款</text>
</view>
<view class="tab-item"
:class="{ active: currentStatus === '1' }"
@click="switchStatus('1')">
<text class="tab-text">待确认</text>
</view>
<view class="tab-item"
:class="{ active: currentStatus === '2' }"
@click="switchStatus('2')">
<text class="tab-text">已完成</text>
</view>
</view>
<!-- 筛选条件 -->
<view class="filter-bar">
<view class="filter-item" @click="showDatePicker('start')">
<text class="filter-label">开始日期</text>
<text class="filter-value">{{ startDate || '选择日期' }}</text>
</view>
<view class="filter-item" @click="showDatePicker('end')">
<text class="filter-label">结束日期</text>
<text class="filter-value">{{ endDate || '选择日期' }}</text>
</view>
<view class="filter-item" @click="showAmountFilter">
<text class="filter-label">按日期筛选</text>
<text class="filter-value">总金额</text>
</view>
</view>
<!-- 总金额显示 -->
<view class="amount-summary" v-if="totalAmount > 0">
<text class="summary-label">重置</text>
<text class="summary-amount">{{ totalAmount }}</text>
</view>
<!-- 订单列表 -->
<view class="order-list">
<view class="order-item" v-for="(item, index) in orderList" :key="index" @click="goToOrderDetail(item)">
<view class="order-header">
<text class="order-number">订单编号:{{ item.order_no }}</text>
<view class="order-status" :class="getStatusClass(item.order_status)">
<text class="status-text">{{ getStatusText(item.order_status) }}</text>
</view>
</view>
<view class="order-content">
<view class="product-info">
<image :src="getFullImageUrl(getFirstImage(item.product_images))"
class="product-image"
mode="aspectFill">
</image>
<view class="product-details">
<text class="product-name">{{ item.product_name }}</text>
<text class="product-price">¥{{ item.unit_price }}</text>
<text class="product-quantity">×{{ item.quantity }}</text>
</view>
</view>
</view>
<view class="order-footer">
<text class="order-time">下单时间:{{ formatTime(item.created_at) }}</text>
<view class="order-summary">
<!-- <text class="summary-text">共{{ item.quantity }}件商品 运费 ¥0.00 合计:</text> -->
<text class="summary-price">¥{{ item.total_amount }}</text>
</view>
</view>
<view class="order-actions">
<!-- <button class="action-btn detail-btn" @click.stop="goToDetail(item)">
查看详情
</button> -->
<button v-if="item.payment_proof_image"
class="action-btn proof-btn"
@click.stop="viewPaymentProof(item)">
查看凭证
</button>
<button v-if="item.order_status === 0"
class="action-btn pay-btn"
@click.stop="payOrder(item)">
立即付款
</button>
<button v-if="item.order_status === 0"
class="action-btn cancel-btn"
@click.stop="cancelOrder(item)">
取消订单
</button>
<!-- <button v-if="item.order_status === 1"
class="action-btn confirm-btn"
@click.stop="confirmOrder(item)">
确认收货
</button> -->
</view>
</view>
</view>
<!-- 空状态 -->
<view class="empty-state" v-if="orderList.length === 0 && !loading">
<uni-icons type="list" size="100" color="#ccc"></uni-icons>
<text class="empty-text">暂无订单</text>
</view>
<!-- 加载更多 -->
<view class="load-more" v-if="hasMore && orderList.length > 0">
<text>加载更多...</text>
</view>
</view>
</template>
<script>
import request from '@/utils/request.js'
export default {
data() {
return {
currentStatus: 'all',
startDate: '',
endDate: '',
totalAmount: 0,
orderList: [],
currentPage: 1,
pageSize: 10,
hasMore: true,
loading: false
}
},
onLoad(options) {
// 检查登录状态
const token = uni.getStorageSync('token')
if (!token) {
uni.reLaunch({
url: '/pages/login/login'
})
return
}
if (options.status) {
this.currentStatus = options.status
}
this.loadOrders()
},
onReachBottom() {
if (this.hasMore && !this.loading) {
this.loadMore()
}
},
methods: {
// 获取完整的图片URL
getFullImageUrl(url) {
return request.getImageUrl(url)
},
// 获取商品的第一张图片
getFirstImage(images) {
if (!images) return ''
if (typeof images === 'string') {
return images.split(',')[0].trim()
}
if (Array.isArray(images) && images.length > 0) {
return images[0]
}
return ''
},
// 切换状态
switchStatus(status) {
this.currentStatus = status
this.currentPage = 1
this.loadOrders()
},
// 显示日期选择器
showDatePicker(type) {
uni.showActionSheet({
itemList: ['今天', '最近7天', '最近30天', '最近90天'],
success: (res) => {
const now = new Date()
let startDate, endDate
switch (res.tapIndex) {
case 0: // 今天
startDate = endDate = this.formatDate(now)
break
case 1: // 最近7天
startDate = this.formatDate(new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000))
endDate = this.formatDate(now)
break
case 2: // 最近30天
startDate = this.formatDate(new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000))
endDate = this.formatDate(now)
break
case 3: // 自定义
startDate = this.formatDate(new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000))
endDate = this.formatDate(now)
break
}
if (type === 'start') {
this.startDate = startDate
} else {
this.endDate = endDate
}
this.currentPage = 1
this.loadOrders()
}
})
},
// 显示金额筛选
showAmountFilter() {
this.startDate = ''
this.endDate = ''
this.currentPage = 1
this.loadOrders()
},
// 加载订单列表
async loadOrders() {
this.loading = true
try {
const params = {
page: this.currentPage,
page_size: this.pageSize
}
if (this.currentStatus !== 'all') {
// 状态映射:前端显示状态 -> 后端查询参数
const statusMap = {
'0': 'pending',
'1': 'confirming',
'2': 'completed',
'3': 'cancelled'
}
params.status = statusMap[this.currentStatus] || this.currentStatus
}
if (this.startDate) {
params.start_date = this.startDate
}
if (this.endDate) {
params.end_date = this.endDate
}
const res = await request.get('/back/user/orders/purchase', params)
if (res.success) {
const data = res.data
if (this.currentPage === 1) {
this.orderList = data.list || []
} else {
this.orderList = [...this.orderList, ...(data.list || [])]
}
this.hasMore = this.orderList.length < data.total
this.totalAmount = data.total_amount || 0
}
} catch (error) {
console.error('加载订单失败:', error)
uni.showToast({
title: '加载失败',
icon: 'none'
})
} finally {
this.loading = false
}
},
// 加载更多
loadMore() {
this.currentPage++
this.loadOrders()
},
// 获取状态样式类
getStatusClass(status) {
const classMap = {
0: 'status-pending',
1: 'status-confirming',
2: 'status-completed',
3: 'status-cancelled'
}
return classMap[status] || ''
},
// 获取状态文本
getStatusText(status) {
const textMap = {
0: '待付款',
1: '待确认',
2: '已完成',
3: '已取消'
}
return textMap[status] || '未知状态'
},
// 格式化时间
formatTime(time) {
if (!time) return ''
const date = new Date(time)
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
},
// 格式化日期
formatDate(date) {
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
},
// 跳转到订单详情
goToDetail(order) {
uni.navigateTo({
url: `/pages/order/detail?id=${order.id}&type=purchase`
})
},
// 跳转到订单详情页面
goToOrderDetail(order) {
uni.navigateTo({
url: `/pages/orders/detail?id=${order.id}&type=purchase`
})
},
// 查看付款凭证
viewPaymentProof(order) {
if (!order.payment_proof_image) {
uni.showToast({
title: '暂无付款凭证',
icon: 'none'
})
return
}
uni.previewImage({
urls: [this.getFullImageUrl(order.payment_proof_image)],
current: 0
})
},
// 支付订单 - 跳转到付款页面
payOrder(order) {
var isSecond=order.product_type == 1 ? false : true
uni.navigateTo({
url: `/pages/payment/purchase?order_id=${order.id}&order_no=${order.order_no}&is_second=${isSecond}`
})
},
// 取消订单
async cancelOrder(order) {
uni.showModal({
title: '确认取消',
content: '确定要取消这个订单吗?',
success: async (res) => {
if (res.confirm) {
try {
const result = await request.put(`/back/user/orders/purchase/${order.id}/cancel`)
if (result.success) {
uni.showToast({
title: '订单已取消',
icon: 'success'
})
this.loadOrders()
} else {
throw new Error(result.message || '取消失败')
}
} catch (error) {
console.error('取消订单失败:', error)
uni.showToast({
title: error.message || '取消失败',
icon: 'none'
})
}
}
}
})
},
// 确认收货
async confirmOrder(order) {
uni.showModal({
title: '确认收货',
content: '确认已收到商品吗?确认后商品将进入您的仓库。',
success: async (res) => {
if (res.confirm) {
try {
const result = await request.put(`/back/user/orders/purchase/${order.id}/confirm`)
if (result.success) {
uni.showToast({
title: '确认收货成功',
icon: 'success'
})
this.loadOrders()
} else {
throw new Error(result.message || '确认失败')
}
} catch (error) {
console.error('确认收货失败:', error)
uni.showToast({
title: error.message || '确认失败',
icon: 'none'
})
}
}
}
})
}
}
}
</script>
<style scoped>
.container {
background-color: #f5f5f5;
min-height: 100vh;
}
/* 状态标签 */
.status-tabs {
background-color: #fff;
display: flex;
padding: 0 30rpx;
}
.tab-item {
flex: 1;
text-align: center;
padding: 30rpx 0;
position: relative;
}
.tab-text {
font-size: 28rpx;
color: #666;
}
.tab-item.active .tab-text {
color: #FF4444;
font-weight: bold;
}
.tab-item.active::after {
content: '';
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
width: 60rpx;
height: 4rpx;
background-color: #FF4444;
}
/* 筛选条件 */
.filter-bar {
background-color: #fff;
display: flex;
padding: 20rpx 30rpx;
border-bottom: 1rpx solid #eee;
}
.filter-item {
flex: 1;
text-align: center;
}
.filter-label {
display: block;
font-size: 24rpx;
color: #999;
margin-bottom: 10rpx;
}
.filter-value {
font-size: 28rpx;
color: #333;
}
/* 总金额 */
.amount-summary {
background-color: #fff;
padding: 20rpx 30rpx;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1rpx solid #eee;
}
.summary-label {
font-size: 28rpx;
color: #007AFF;
}
.summary-amount {
font-size: 32rpx;
font-weight: bold;
color: #FF4444;
}
/* 订单列表 */
.order-list {
padding: 20rpx;
}
.order-item {
background-color: #fff;
border-radius: 16rpx;
margin-bottom: 20rpx;
overflow: hidden;
}
.order-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 30rpx;
border-bottom: 1rpx solid #f5f5f5;
}
.order-number {
font-size: 24rpx;
color: #666;
}
.order-status {
padding: 8rpx 16rpx;
border-radius: 20rpx;
font-size: 24rpx;
}
.status-pending {
background-color: #FFF2E6;
color: #FF8800;
}
.status-confirming {
background-color: #E6F7FF;
color: #1890FF;
}
.status-completed {
background-color: #F6FFED;
color: #52C41A;
}
.status-cancelled {
background-color: #FFF1F0;
color: #FF4D4F;
}
.order-content {
padding: 30rpx;
}
.product-info {
display: flex;
}
.product-image {
width: 160rpx;
height: 120rpx;
border-radius: 8rpx;
margin-right: 20rpx;
background-color: #f5f5f5;
}
.product-details {
flex: 1;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.product-name {
font-size: 28rpx;
color: #333;
font-weight: bold;
}
.product-price {
font-size: 32rpx;
color: #FF4444;
font-weight: bold;
}
.product-quantity {
font-size: 24rpx;
color: #999;
}
.order-footer {
padding: 30rpx;
border-top: 1rpx solid #f5f5f5;
}
.order-time {
display: block;
font-size: 24rpx;
color: #999;
margin-bottom: 20rpx;
}
.order-summary {
display: flex;
justify-content: space-between;
align-items: center;
}
.summary-text {
font-size: 24rpx;
color: #666;
}
.summary-price {
font-size: 32rpx;
color: #FF4444;
font-weight: bold;
}
.order-actions {
display: flex;
justify-content: flex-end;
padding: 30rpx;
gap: 20rpx;
border-top: 1rpx solid #f5f5f5;
}
.action-btn {
padding: 16rpx 32rpx;
border-radius: 8rpx;
font-size: 24rpx;
border: 1rpx solid #ddd;
}
.detail-btn {
background-color: #fff;
color: #666;
}
.proof-btn {
background-color: #1890FF;
color: #fff;
border-color: #1890FF;
}
.pay-btn {
background-color: #FF4444;
color: #fff;
border-color: #FF4444;
}
.cancel-btn {
background-color: #fff;
color: #999;
}
.confirm-btn {
background-color: #52C41A;
color: #fff;
border-color: #52C41A;
}
/* 空状态 */
.empty-state {
text-align: center;
padding: 200rpx 0;
}
.empty-state uni-icons {
margin-bottom: 40rpx;
}
.empty-text {
font-size: 28rpx;
color: #999;
}
/* 加载更多 */
.load-more {
text-align: center;
padding: 40rpx;
color: #999;
font-size: 24rpx;
}
</style>
+411
View File
@@ -0,0 +1,411 @@
<template>
<view class="container">
<!-- 页面标题 -->
<view class="page-header">
<text class="page-title">收款方式</text>
<text class="page-subtitle">设置您的主收款码和副收款码</text>
</view>
<!-- 主收款码 -->
<view class="payment-section">
<view class="section-header">
<text class="section-title">主收款码</text>
<text class="section-subtitle">优先使用的收款二维码</text>
</view>
<view class="qr-upload-container">
<view class="qr-preview" @tap="uploadMainQr">
<image v-if="paymentInfo.main_payment_qr_image"
:src="getFullImageUrl(paymentInfo.main_payment_qr_image)"
class="qr-image"
mode="aspectFit">
</image>
<view v-else class="qr-placeholder">
<uni-icons type="camera" size="40" color="#ccc"></uni-icons>
<text class="placeholder-text">点击上传主收款码</text>
</view>
</view>
<view class="upload-tips">
<text class="tip-text">建议上传四大行收款码</text>
</view>
</view>
</view>
<!-- 副收款码 -->
<view class="payment-section">
<view class="section-header">
<text class="section-title">副收款码</text>
<text class="section-subtitle">备用收款二维码</text>
</view>
<view class="qr-upload-container">
<view class="qr-preview" @tap="uploadSubQr">
<image v-if="paymentInfo.sub_payment_qr_image"
:src="getFullImageUrl(paymentInfo.sub_payment_qr_image)"
class="qr-image"
mode="aspectFit">
</image>
<view v-else class="qr-placeholder">
<uni-icons type="camera" size="40" color="#ccc"></uni-icons>
<text class="placeholder-text">点击上传副收款码</text>
</view>
</view>
<view class="upload-tips">
<text class="tip-text">可选,作为备用收款方式</text>
</view>
</view>
</view>
<!-- 保存按钮 -->
<view class="save-section">
<button class="save-btn" @tap="savePaymentInfo" :disabled="saving">
<text v-if="saving">保存中...</text>
<text v-else>保存收款方式</text>
</button>
</view>
<!-- 使用说明 -->
<view class="help-section">
<view class="help-header">
<uni-icons type="help" size="20" color="#999"></uni-icons>
<text class="help-title">使用说明</text>
</view>
<view class="help-content">
<text class="help-text">1. 主收款码会优先显示给买家</text>
<text class="help-text">2. 副收款码作为备用收款方式</text>
<text class="help-text">3. 建议上传清晰的收款二维码图片</text>
<text class="help-text">4. 支持所有银行及三方等收款码</text>
</view>
</view>
</view>
</template>
<script>
import request from '@/utils/request.js'
export default {
data() {
return {
paymentInfo: {
main_payment_qr_image: '',
sub_payment_qr_image: '',
},
saving: false,
loading: false,
ismain:false,
issub:false,
}
},
onLoad() {
// 检查登录状态
const token = uni.getStorageSync('token')
if (!token) {
uni.reLaunch({
url: '/pages/login/login'
})
return
}
this.loadPaymentInfo()
},
methods: {
// 获取完整的图片URL
getFullImageUrl(url) {
return request.getImageUrl(url)
},
// 加载收款方式信息
async loadPaymentInfo() {
this.loading = true
try {
const res = await request.get('/back/user/payment/info')
if (res.success) {
this.paymentInfo = res.data
if(this.paymentInfo.main_payment_qr_image){
this.ismain=true
}
if(this.paymentInfo.sub_payment_qr_image){
this.issub=true
}
}
} catch (error) {
console.error('加载收款方式失败:', error)
uni.showToast({
title: '加载失败',
icon: 'none'
})
} finally {
this.loading = false
}
},
// 上传主收款码
uploadMainQr() {
if(this.ismain){
uni.showToast({
title:"已上传"
})
return
}
this.chooseAndUploadImage('main')
},
// 上传副收款码
uploadSubQr() {
if(this.issub){
uni.showToast({
title:"已上传"
})
return
}
this.chooseAndUploadImage('sub')
},
// 选择并上传图片
chooseAndUploadImage(type) {
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['camera', 'album'],
success: async (res) => {
const filePath = res.tempFilePaths[0]
await this.uploadImage(filePath, type)
},
fail: (err) => {
console.error('选择图片失败:', err)
uni.showToast({
title: '选择图片失败',
icon: 'none'
})
}
})
},
// 上传图片
async uploadImage(filePath, type) {
try {
uni.showLoading({
title: '上传中...',
mask: true
})
const token = uni.getStorageSync('token')
const res = await request.upload('/back/upload', filePath, {
token: token,
name: 'file'
})
if (res.success) {
// 更新对应的收款码
if (type === 'main') {
this.paymentInfo.main_payment_qr_image = res.data.url
} else {
this.paymentInfo.sub_payment_qr_image = res.data.url
}
uni.showToast({
title: '上传成功',
icon: 'success'
})
} else {
throw new Error(res.message || '上传失败')
}
} catch (error) {
console.error('上传图片失败:', error)
uni.showToast({
title: '上传失败',
icon: 'none'
})
} finally {
uni.hideLoading()
}
},
// 保存收款方式信息
async savePaymentInfo() {
if (!this.paymentInfo.main_payment_qr_image && !this.paymentInfo.sub_payment_qr_image) {
uni.showToast({
title: '请至少上传一个收款码',
icon: 'none'
})
return
}
this.saving = true
try {
const res = await request.put('/back/user/payment/info', this.paymentInfo)
if (res.success) {
this.paymentInfo = res.data
uni.showToast({
title: '保存成功',
icon: 'success'
})
this.loadPaymentInfo()
} else {
throw new Error(res.message || '保存失败')
}
} catch (error) {
console.error('保存收款方式失败:', error)
uni.showToast({
title: '保存失败',
icon: 'none'
})
} finally {
this.saving = false
}
}
}
}
</script>
<style scoped>
.container {
background-color: #f5f5f5;
min-height: 100vh;
padding: 20rpx;
}
.page-header {
background: white;
padding: 40rpx 30rpx;
border-radius: 20rpx;
margin-bottom: 20rpx;
text-align: center;
}
.page-title {
font-size: 36rpx;
font-weight: bold;
color: #333;
display: block;
margin-bottom: 10rpx;
}
.page-subtitle {
font-size: 28rpx;
color: #666;
}
.payment-section {
background: white;
border-radius: 20rpx;
padding: 30rpx;
margin-bottom: 20rpx;
}
.section-header {
margin-bottom: 30rpx;
}
.section-title {
font-size: 32rpx;
font-weight: bold;
color: #333;
display: block;
margin-bottom: 8rpx;
}
.section-subtitle {
font-size: 26rpx;
color: #666;
}
.qr-upload-container {
display: flex;
flex-direction: column;
align-items: center;
}
.qr-preview {
width: 400rpx;
height: 400rpx;
border: 2rpx dashed #ddd;
border-radius: 20rpx;
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 20rpx;
overflow: hidden;
}
.qr-image {
width: 100%;
height: 100%;
}
.qr-placeholder {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: #ccc;
}
.placeholder-text {
font-size: 26rpx;
color: #999;
margin-top: 15rpx;
}
.upload-tips {
text-align: center;
}
.tip-text {
font-size: 24rpx;
color: #999;
}
.save-section {
margin: 40rpx 0;
}
.save-btn {
width: 100%;
height: 90rpx;
background: linear-gradient(135deg, #FF4444 0%, #FF6666 100%);
border: none;
border-radius: 45rpx;
color: white;
font-size: 32rpx;
font-weight: bold;
display: flex;
align-items: center;
justify-content: center;
}
.save-btn:disabled {
background: #ccc;
}
.help-section {
background: white;
border-radius: 20rpx;
padding: 30rpx;
margin-bottom: 40rpx;
}
.help-header {
display: flex;
align-items: center;
margin-bottom: 20rpx;
}
.help-title {
font-size: 30rpx;
font-weight: bold;
color: #333;
margin-left: 10rpx;
}
.help-content {
display: flex;
flex-direction: column;
gap: 15rpx;
}
.help-text {
font-size: 26rpx;
color: #666;
line-height: 1.5;
}
</style>
+805
View File
@@ -0,0 +1,805 @@
<template>
<view class="container">
<!-- 页面标题 -->
<view class="page-header">
<text class="page-title">确认付款</text>
</view>
<!-- 订单信息 -->
<view class="order-section">
<view class="section-title">订单信息</view>
<view class="order-item">
<image :src="getFullImageUrl(productInfo.image)" class="product-image" mode="aspectFill" v-if="productInfo.image"></image>
<view class="product-details">
<text class="product-name">{{ productInfo.name }}</text>
<view class="product-price-info">
<text class="unit-price">单价:¥{{ orderInfo.unit_price }}</text>
<text class="quantity">数量:{{ orderInfo.quantity }}</text>
</view>
</view>
</view>
<view class="total-amount">
<text class="total-label">总金额:</text>
<text class="total-price">¥{{ orderInfo.total_amount }}</text>
</view>
</view>
<!-- 收货地址 -->
<view class="address-section">
<view class="section-title">收货地址</view>
<view class="address-selector" @tap="selectAddress">
<view class="address-content" v-if="selectedAddress">
<view class="address-info">
<text class="consignee">{{ selectedAddress.consignee_name }}</text>
<text class="phone">{{ selectedAddress.consignee_phone }}</text>
</view>
<text class="address-detail">{{ formatAddress(selectedAddress) }}</text>
</view>
<view class="no-address" v-else>
<text class="no-address-text">请选择收货地址</text>
</view>
<uni-icons type="right" size="16" color="#ccc"></uni-icons>
</view>
</view>
<!-- 付款方式 -->
<view class="payment-section">
<view class="section-title">请扫码付款</view>
<view class="payment-qr-container">
<!-- 管理员付款码(一级商品) -->
<view class="qr-section" v-if="orderInfo.product_type === 1">
<view class="qr-title">
<text class="qr-label">请扫描以下二维码付款</text>
<text class="qr-subtitle">官方收款账户</text>
</view>
<view class="qr-code-wrapper">
<image :src="getFullImageUrl(adminPaymentQr.main)"
class="qr-code"
mode="aspectFit"
v-if="adminPaymentQr.main"
@tap="previewQrCode(adminPaymentQr.main)">
</image>
<view class="qr-placeholder" v-else>
<text class="placeholder-text">暂无付款码</text>
</view>
</view>
<view class="backup-qr" v-if="adminPaymentQr.sub">
<text class="backup-label">备用付款码</text>
<image :src="getFullImageUrl(adminPaymentQr.sub)"
class="backup-qr-image"
mode="aspectFit"
@tap="previewQrCode(adminPaymentQr.sub)">
</image>
</view>
</view>
<!-- 卖家付款码(二级商品) -->
<view class="qr-section" v-if="orderInfo.product_type === 2">
<view class="qr-title">
<text class="qr-label">请扫描以下二维码付款</text>
<text class="qr-subtitle">卖家收款账户</text>
</view>
<view class="seller-info">
<image :src="getFullImageUrl(sellerInfo.avatar)" class="seller-avatar" mode="aspectFill" v-if="sellerInfo.avatar"></image>
<view class="seller-avatar-placeholder" v-else>
<uni-icons type="person" size="30" color="#ccc"></uni-icons>
</view>
<view class="seller-details">
<text class="seller-name">{{ sellerInfo.customer_name || sellerInfo.real_name }}</text>
<text class="seller-code">ID: {{ sellerInfo.identity_code }}</text>
</view>
</view>
<view class="qr-code-wrapper">
<image :src="getFullImageUrl(sellerPaymentQr.main)"
class="qr-code"
mode="aspectFit"
v-if="sellerPaymentQr.main"
@tap="previewQrCode(sellerPaymentQr.main)">
</image>
<view class="qr-placeholder" v-else>
<text class="placeholder-text">卖家暂未设置付款码</text>
</view>
</view>
<view class="backup-qr" v-if="sellerPaymentQr.sub">
<text class="backup-label">备用付款码</text>
<image :src="getFullImageUrl(sellerPaymentQr.sub)"
class="backup-qr-image"
mode="aspectFit"
@tap="previewQrCode(sellerPaymentQr.sub)">
</image>
</view>
</view>
</view>
</view>
<!-- 上传付款凭证 -->
<view class="upload-section">
<view class="section-title">上传付款凭证</view>
<view class="upload-container">
<view class="upload-item" @tap="uploadPaymentProof">
<image v-if="paymentProofImage"
:src="getFullImageUrl(paymentProofImage)"
class="proof-image"
mode="aspectFill">
</image>
<view v-else class="upload-placeholder">
<uni-icons type="camera" size="40" color="#ccc"></uni-icons>
<text class="upload-text">点击上传付款截图</text>
</view>
</view>
<view class="upload-tips">
<text class="tip-text">请上传完整的付款截图,包含金额和时间信息</text>
</view>
</view>
</view>
<!-- 提交按钮 -->
<view class="submit-section">
<view class="action-buttons">
<button class="cancel-btn" @tap="cancelOrder" v-if="canCancel">
取消订单
</button>
<button class="submit-btn" @tap="submitOrder" :disabled="!canSubmit || submitting">
<text v-if="submitting">提交中...</text>
<text v-else>提交付款凭证</text>
</button>
</view>
</view>
</view>
</template>
<script>
import request from '@/utils/request.js'
export default {
data() {
return {
orderId: '',
orderNo: '',
orderInfo: {},
productInfo: {
name: '',
image: ''
},
selectedAddress: null,
adminPaymentQr: {
main: '',
sub: ''
},
sellerInfo: {},
sellerPaymentQr: {
main: '',
sub: ''
},
paymentProofImage: '',
submitting: false,
canCancel: true,
productType:1
}
},
computed: {
canSubmit() {
return this.paymentProofImage && !this.submitting
}
},
onLoad(options) {
// 检查登录状态
const token = uni.getStorageSync('token')
if (!token) {
uni.reLaunch({
url: '/pages/login/login'
})
return
}
// 获取订单信息
this.orderId = options.order_id || ''
this.orderNo = options.order_no || ''
if(options.is_second=="true"){
this.productType=2
}else
{
this.productType=1
}
if (!this.orderId) {
uni.showToast({
title: '订单信息有误',
icon: 'none'
})
setTimeout(() => {
uni.navigateBack()
}, 1500)
return
}
this.loadOrderData()
},
methods: {
// 获取完整的图片URL
getFullImageUrl(url) {
return request.getImageUrl(url)
},
// 加载订单数据
async loadOrderData() {
try {
// 获取订单详情
const orderRes = await request.get(`/back/user/orders/purchase?order_id=${this.orderId}`)
if (orderRes.success && orderRes.data.list && orderRes.data.list.length > 0) {
this.orderInfo = orderRes.data.list[0]
this.selectedAddress = this.orderInfo.address
// 设置商品信息
this.productInfo = {
name: this.orderInfo.product_name,
image: this.getFirstImage(this.orderInfo.product_images)
}
// 检查订单状态
if (this.orderInfo.order_status !== 0) {
this.canCancel = false
}
// 如果是二级商品,获取卖家信息
if (this.orderInfo.product_type === 2 && this.orderInfo.seller_id) {
this.sellerInfo = this.orderInfo.seller
}
// 加载付款信息
await this.loadPaymentInfo()
} else {
throw new Error('订单不存在')
}
} catch (error) {
console.error('加载订单失败:', error)
uni.showToast({
title: '加载订单失败',
icon: 'none'
})
setTimeout(() => {
uni.navigateBack()
}, 1500)
}
},
// 获取商品的第一张图片
getFirstImage(images) {
if (!images) return ''
if (typeof images === 'string') {
return images.split(',')[0].trim()
}
if (Array.isArray(images) && images.length > 0) {
return images[0]
}
return ''
},
// 加载付款信息
async loadPaymentInfo() {
try {
if (this.orderInfo.product_type === 1) { // 一级商品
// 加载管理员付款码
const res = await request.get('/back/admin/payment/info')
if (res.success) {
this.adminPaymentQr = {
main: res.data.main_payment_qr_image || '',
sub: res.data.sub_payment_qr_image || ''
}
}
} else { // 二级商品
// 加载卖家付款码
const res = await request.get(`/back/user/seller/${this.orderInfo.seller_id}/payment`)
if (res.success) {
this.sellerPaymentQr = {
main: res.data.main_payment_qr_image || '',
sub: res.data.sub_payment_qr_image || ''
}
}
}
} catch (error) {
console.error('加载付款信息失败:', error)
}
},
// 格式化地址
formatAddress(address) {
if (!address) return ''
return `${address.province} ${address.city} ${address.district} ${address.detail_address}`
},
// 选择收货地址
selectAddress() {
uni.navigateTo({
url: '/pages/address/select'
})
},
// 预览二维码
previewQrCode(qrCode) {
if (!qrCode) return
uni.previewImage({
urls: [this.getFullImageUrl(qrCode)],
current: 0
})
},
// 上传付款凭证
uploadPaymentProof() {
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['camera', 'album'],
success: async (res) => {
const filePath = res.tempFilePaths[0]
await this.uploadImage(filePath)
},
fail: (err) => {
console.error('选择图片失败:', err)
uni.showToast({
title: '选择图片失败',
icon: 'none'
})
}
})
},
// 上传图片
async uploadImage(filePath) {
try {
uni.showLoading({
title: '上传中...',
mask: true
})
const token = uni.getStorageSync('token')
const res = await request.upload('/back/upload', filePath, {
token: token,
name: 'file'
})
if (res.success) {
this.paymentProofImage = res.data.url
uni.showToast({
title: '上传成功',
icon: 'success'
})
} else {
throw new Error(res.message || '上传失败')
}
} catch (error) {
console.error('上传图片失败:', error)
uni.showToast({
title: '上传失败',
icon: 'none'
})
} finally {
uni.hideLoading()
}
},
// 提交付款凭证
async submitOrder() {
if (!this.canSubmit) {
if (!this.paymentProofImage) {
uni.showToast({
title: '请上传付款凭证',
icon: 'none'
})
}
return
}
this.submitting = true
try {
const res = await request.put(`/back/user/orders/purchase/${this.orderId}/payment`, {
payment_proof_image: this.paymentProofImage,
product_type :this.productType
})
if (res.success) {
uni.showToast({
title: '付款凭证提交成功',
icon: 'success'
})
// 延迟跳转到订单页面
setTimeout(() => {
uni.redirectTo({
url: '/pages/orders/orders'
})
}, 1500)
} else {
throw new Error(res.message || '提交付款凭证失败')
}
} catch (error) {
console.error('提交付款凭证失败:', error)
uni.showToast({
title: error.message || '提交失败',
icon: 'none'
})
} finally {
this.submitting = false
}
},
// 取消订单
async cancelOrder() {
uni.showModal({
title: '确认取消',
content: '确定要取消这个订单吗?',
success: async (res) => {
if (res.confirm) {
try {
const result = await request.put(`/back/user/orders/purchase/${this.orderId}/cancel`)
if (result.success) {
uni.showToast({
title: '订单已取消',
icon: 'success'
})
setTimeout(() => {
uni.navigateBack()
}, 1500)
} else {
throw new Error(result.message || '取消订单失败')
}
} catch (error) {
console.error('取消订单失败:', error)
uni.showToast({
title: error.message || '取消失败',
icon: 'none'
})
}
}
}
})
}
}
}
</script>
<style scoped>
.container {
background-color: #f5f5f5;
min-height: 100vh;
padding-bottom: 120rpx;
}
.page-header {
background: white;
padding: 30rpx;
text-align: center;
border-bottom: 1rpx solid #eee;
}
.page-title {
font-size: 36rpx;
font-weight: bold;
color: #333;
}
.order-section,
.address-section,
.payment-section,
.upload-section {
background: white;
margin: 20rpx;
border-radius: 20rpx;
padding: 30rpx;
}
.section-title {
font-size: 30rpx;
font-weight: bold;
color: #333;
margin-bottom: 20rpx;
}
.order-item {
display: flex;
align-items: center;
margin-bottom: 20rpx;
}
.product-image {
width: 120rpx;
height: 120rpx;
border-radius: 10rpx;
margin-right: 20rpx;
}
.product-details {
flex: 1;
}
.product-name {
font-size: 28rpx;
color: #333;
font-weight: bold;
display: block;
margin-bottom: 10rpx;
}
.product-price-info {
display: flex;
gap: 20rpx;
}
.unit-price,
.quantity {
font-size: 24rpx;
color: #666;
}
.total-amount {
display: flex;
justify-content: space-between;
align-items: center;
padding-top: 20rpx;
border-top: 1rpx solid #eee;
}
.total-label {
font-size: 28rpx;
color: #333;
}
.total-price {
font-size: 36rpx;
color: #FF4444;
font-weight: bold;
}
.address-selector {
display: flex;
align-items: center;
justify-content: space-between;
padding: 20rpx;
background: #f8f8f8;
border-radius: 15rpx;
min-height: 100rpx;
}
.address-content {
flex: 1;
}
.address-info {
display: flex;
gap: 20rpx;
margin-bottom: 8rpx;
}
.consignee {
font-size: 28rpx;
color: #333;
font-weight: bold;
}
.phone {
font-size: 28rpx;
color: #666;
}
.address-detail {
font-size: 26rpx;
color: #666;
line-height: 1.4;
}
.no-address {
flex: 1;
text-align: center;
}
.no-address-text {
font-size: 28rpx;
color: #999;
}
.payment-qr-container {
text-align: center;
}
.qr-section {
margin-bottom: 30rpx;
}
.qr-title {
margin-bottom: 20rpx;
}
.qr-label {
font-size: 28rpx;
color: #333;
display: block;
margin-bottom: 8rpx;
}
.qr-subtitle {
font-size: 24rpx;
color: #666;
}
.seller-info {
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 20rpx;
padding: 15rpx;
background: #f8f8f8;
border-radius: 15rpx;
}
.seller-avatar {
width: 60rpx;
height: 60rpx;
border-radius: 30rpx;
margin-right: 15rpx;
}
.seller-avatar-placeholder {
width: 60rpx;
height: 60rpx;
border-radius: 30rpx;
background: #e5e5e5;
display: flex;
align-items: center;
justify-content: center;
margin-right: 15rpx;
}
.seller-details {
text-align: left;
}
.seller-name {
font-size: 26rpx;
color: #333;
font-weight: bold;
display: block;
margin-bottom: 5rpx;
}
.seller-code {
font-size: 22rpx;
color: #666;
}
.qr-code-wrapper {
display: flex;
justify-content: center;
margin-bottom: 20rpx;
}
.qr-code {
width: 400rpx;
height: 400rpx;
border: 2rpx solid #eee;
border-radius: 15rpx;
}
.qr-placeholder {
width: 400rpx;
height: 400rpx;
border: 2rpx dashed #ddd;
border-radius: 15rpx;
display: flex;
align-items: center;
justify-content: center;
}
.placeholder-text {
font-size: 26rpx;
color: #999;
}
.backup-qr {
margin-top: 20rpx;
}
.backup-label {
font-size: 24rpx;
color: #666;
display: block;
margin-bottom: 10rpx;
}
.backup-qr-image {
width: 200rpx;
height: 200rpx;
border: 1rpx solid #eee;
border-radius: 10rpx;
}
.upload-container {
text-align: center;
}
.upload-item {
width: 400rpx;
height: 300rpx;
margin: 0 auto 20rpx;
border: 2rpx dashed #ddd;
border-radius: 15rpx;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
.proof-image {
width: 100%;
height: 100%;
}
.upload-placeholder {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
color: #ccc;
}
.upload-text {
font-size: 26rpx;
color: #999;
margin-top: 15rpx;
}
.upload-tips {
margin-top: 10rpx;
}
.tip-text {
font-size: 24rpx;
color: #666;
line-height: 1.4;
}
.submit-section {
padding: 40rpx 30rpx;
}
.action-buttons {
display: flex;
gap: 20rpx;
}
.cancel-btn {
flex: 1;
height: 80rpx;
background: #f5f5f5;
border: 1rpx solid #ddd;
border-radius: 40rpx;
color: #666;
font-size: 32rpx;
font-weight: bold;
display: flex;
align-items: center;
justify-content: center;
}
.submit-btn {
flex: 2;
height: 80rpx;
background: linear-gradient(135deg, #FF4444 0%, #FF6666 100%);
border: none;
border-radius: 40rpx;
color: white;
font-size: 32rpx;
font-weight: bold;
display: flex;
align-items: center;
justify-content: center;
}
.submit-btn:disabled {
background: #ccc;
}
</style>
+781
View File
@@ -0,0 +1,781 @@
<template>
<view class="container">
<!-- 商品图片轮播 -->
<view class="image-section">
<swiper class="image-swiper" :indicator-dots="imageList.length > 1" indicator-color="rgba(255,255,255,0.5)" indicator-active-color="#FF4444" :autoplay="false" :circular="true">
<swiper-item v-for="(image, index) in imageList" :key="index">
<image :src="getFullImageUrl(image)" class="product-image" mode="aspectFill" @tap="previewImage(index)"></image>
</swiper-item>
</swiper>
<view class="image-count" v-if="imageList.length > 1">
<text>{{ currentImageIndex + 1 }}/{{ imageList.length }}</text>
</view>
</view>
<!-- 商品基本信息 -->
<view class="product-info-section">
<view class="price-section">
<view class="current-price">
<text class="price-symbol">¥</text>
<text class="price-value">{{ productInfo.current_price || productInfo.selling_price }}</text>
</view>
<view class="original-price" v-if="productInfo.original_price && productInfo.original_price != productInfo.current_price">
<text class="original-price-text">原价 ¥{{ productInfo.original_price }}</text>
</view>
</view>
<view class="product-title">
<text class="product-name">{{ productInfo.product_name }}</text>
</view>
<view class="product-stats">
<text class="stats-item">销量 {{ productInfo.sales_count || 0 }}</text>
<text class="stats-item">库存 {{ productInfo.stock_quantity || productInfo.quantity || 0 }}</text>
<text class="stats-item">浏览 {{ productInfo.view_count || 0 }}</text>
</view>
</view>
<!-- 卖家信息(仅二级商品显示) -->
<view class="seller-section" v-if="productType === 'secondary' && productInfo.seller">
<view class="section-title">卖家信息</view>
<view class="seller-info">
<image :src="getFullImageUrl(productInfo.seller.avatar)" class="seller-avatar" mode="aspectFill" v-if="productInfo.seller.avatar"></image>
<view class="seller-avatar-placeholder" v-else>
<uni-icons type="person" size="40" color="#ccc"></uni-icons>
</view>
<view class="seller-details">
<text class="seller-name">{{ productInfo.seller.real_name || productInfo.seller.customer_name }}</text>
<text class="seller-code">ID: {{ productInfo.seller.identity_code }}</text>
</view>
</view>
</view>
<!-- 商品描述 -->
<view class="description-section" v-if="productInfo.product_description">
<view class="section-title">商品描述</view>
<view class="description-content">
<text class="description-text">{{ productInfo.product_description }}</text>
</view>
</view>
<!-- 购买数量选择弹窗 -->
<uni-popup ref="quantityPopup" type="bottom" background-color="#fff" border-radius="20rpx 20rpx 0 0">
<view class="quantity-popup">
<view class="popup-content">
<view class="popup-header">
<text class="popup-title">选择购买数量</text>
<view class="close-btn" @tap="closeQuantityPopup">
<uni-icons type="close" size="20" color="#999"></uni-icons>
</view>
</view>
<view class="popup-product-info">
<image :src="getFullImageUrl(getFirstImage(productInfo.product_images))" class="popup-product-image" mode="aspectFill"></image>
<view class="popup-product-details">
<text class="popup-product-name">{{ productInfo.product_name }}</text>
<text class="popup-product-price">¥{{ productInfo.current_price || productInfo.selling_price }}</text>
</view>
</view>
<view class="quantity-selector">
<text class="quantity-label">购买数量</text>
<view class="quantity-controls">
<view class="quantity-btn" @tap="decreaseQuantity" :class="{ disabled: selectedQuantity <= 1 }">
<uni-icons type="minus" size="16" color="#666"></uni-icons>
</view>
<input class="quantity-input" type="number" v-model="selectedQuantity" @input="onQuantityInput" />
<view class="quantity-btn" @tap="increaseQuantity" :class="{ disabled: selectedQuantity >= maxQuantity }">
<uni-icons type="plus" size="16" color="#666"></uni-icons>
</view>
</view>
<text class="stock-info">库存{{ maxQuantity }}件</text>
</view>
<view class="total-price">
<text class="total-label">总价:</text>
<text class="total-amount">¥{{ (selectedQuantity * (productInfo.current_price || productInfo.selling_price)).toFixed(2) }}</text>
</view>
</view>
<view class="popup-footer">
<button class="confirm-buy-btn" @tap="confirmPurchase">
立即购买
</button>
</view>
</view>
</uni-popup>
<!-- 底部购买栏 -->
<view class="bottom-bar">
<button class="buy-btn" @tap="showQuantityPopup" :disabled="!canPurchase">
<text v-if="!canPurchase">暂时无法购买</text>
<text v-else>立即购买</text>
</button>
</view>
<!-- 加载状态 -->
<view class="loading-overlay" v-if="loading">
<text class="loading-text">加载中...</text>
</view>
</view>
</template>
<script>
import request from '@/utils/request.js'
export default {
data() {
return {
productId: '',
productType: '', // 'primary' 或 'secondary'
productInfo: {},
imageList: [],
currentImageIndex: 0,
selectedQuantity: 1,
maxQuantity: 0,
loading: false,
canPurchase: true
}
},
onLoad(options) {
// 检查登录状态
const token = uni.getStorageSync('token')
if (!token) {
uni.reLaunch({
url: '/pages/login/login'
})
return
}
// 显示安全提示弹窗
this.showSecurityAlert()
if (options.id && options.type) {
this.productId = options.id
this.productType = options.type
this.loadProductDetail()
} else {
uni.showToast({
title: '商品信息有误',
icon: 'none'
})
setTimeout(() => {
uni.navigateBack()
}, 1500)
}
},
methods: {
// 显示安全提示弹窗
showSecurityAlert() {
// 检查是否已经显示过,避免重复提示
const hasShownAlert = uni.getStorageSync('security_alert_shown')
if (hasShownAlert) {
return
}
uni.showModal({
title: '安全提示',
content: '为了您的账户安全,请在使用过程中:\n\n• 关闭WiFi连接\n• 关闭位置服务\n• 关闭蓝牙功能\n• 关闭热点功能\n\n这样可以防止信息泄露,保护您的隐私安全。',
showCancel: true,
cancelText: '知道了',
confirmText: '不再提示',
success: (res) => {
if (res.confirm) {
// 用户选择不再提示,记录到本地存储
uni.setStorageSync('security_alert_shown', true)
}
// 无论用户选择什么,都已经显示过提示了
}
})
},
// 获取完整的图片URL
getFullImageUrl(url) {
return request.getImageUrl(url)
},
// 获取商品的第一张图片
getFirstImage(images) {
if (!images) return ''
// 如果是逗号分隔的字符串
if (typeof images === 'string') {
return images.split(',')[0].trim()
}
// 如果是数组
if (Array.isArray(images) && images.length > 0) {
return images[0]
}
return ''
},
// 加载商品详情
async loadProductDetail() {
this.loading = true
try {
let url = ''
if (this.productType === 'primary') {
url = `/back/user/products/primary/${this.productId}`
} else {
url = `/back/user/products/secondary/${this.productId}`
}
const res = await request.get(url)
if (res.success) {
this.productInfo = res.data
this.processProductImages()
this.calculateMaxQuantity()
this.checkCanPurchase()
} else {
throw new Error(res.message || '加载商品详情失败')
}
} catch (error) {
console.error('加载商品详情失败:', error)
uni.showToast({
title: '加载失败',
icon: 'none'
})
} finally {
this.loading = false
}
},
// 处理商品图片
processProductImages() {
if (this.productInfo.product_images) {
if (typeof this.productInfo.product_images === 'string') {
this.imageList = this.productInfo.product_images.split(',').map(img => img.trim()).filter(img => img)
} else if (Array.isArray(this.productInfo.product_images)) {
this.imageList = this.productInfo.product_images
}
}
// 如果没有图片,设置默认图片
if (this.imageList.length === 0) {
this.imageList = ['/static/images/default-product.png']
}
},
// 计算最大购买数量
calculateMaxQuantity() {
if (this.productType === 'primary') {
this.maxQuantity = this.productInfo.stock_quantity || 0
} else {
this.maxQuantity = this.productInfo.quantity || 0
}
},
// 检查是否可以购买
checkCanPurchase() {
if (this.maxQuantity <= 0) {
this.canPurchase = false
return
}
// 如果是二级商品,需要检查是否是自己的商品
if (this.productType === 'secondary') {
const userInfo = uni.getStorageSync('userInfo')
if (userInfo && this.productInfo.seller_id === userInfo.id) {
this.canPurchase = false
return
}
}
this.canPurchase = true
},
// 预览图片
previewImage(index) {
const urls = this.imageList.map(img => this.getFullImageUrl(img))
uni.previewImage({
urls: urls,
current: index
})
},
// 显示数量选择弹窗
showQuantityPopup() {
if (!this.canPurchase) return
this.selectedQuantity = 1
this.$refs.quantityPopup.open()
},
// 关闭数量选择弹窗
closeQuantityPopup() {
this.$refs.quantityPopup.close()
},
// 减少数量
decreaseQuantity() {
if (this.selectedQuantity > 1) {
this.selectedQuantity--
}
},
// 增加数量
increaseQuantity() {
if (this.selectedQuantity < this.maxQuantity) {
this.selectedQuantity++
}
},
// 数量输入处理
onQuantityInput(e) {
let value = parseInt(e.detail.value) || 1
if (value < 1) value = 1
if (value > this.maxQuantity) value = this.maxQuantity
this.selectedQuantity = value
},
// 确认购买
async confirmPurchase() {
if (this.selectedQuantity <= 0 || this.selectedQuantity > this.maxQuantity) {
uni.showToast({
title: '购买数量有误',
icon: 'none'
})
return
}
// 先检查是否有收货地址
try {
const addressRes = await request.get('/back/user/addresses')
if (!addressRes.success || !addressRes.data || addressRes.data.length === 0) {
uni.showModal({
title: '提示',
content: '请先设置收货地址',
success: (res) => {
if (res.confirm) {
uni.navigateTo({
url: '/pages/address/edit'
})
}
}
})
return
}
// 创建订单
const orderData = {
product_id: parseInt(this.productId),
product_type: this.productType === 'primary' ? 1 : 2,
product_name: this.productInfo.product_name,
product_images: this.getFirstImage(this.productInfo.product_images),
unit_price: this.productInfo.current_price || this.productInfo.selling_price,
quantity: this.selectedQuantity,
total_amount: parseFloat((this.selectedQuantity * (this.productInfo.current_price || this.productInfo.selling_price)).toFixed(2)),
address_id: addressRes.data.find(addr => addr.is_default === 1)?.id || addressRes.data[0].id,
remark: ''
}
uni.showLoading({
title: '创建订单中...',
mask: true
})
const orderRes = await request.post('/back/user/orders/purchase', orderData)
var isSecond=this.productType === 'primary' ? false : true
if (orderRes.success) {
uni.hideLoading()
// 关闭弹窗
this.closeQuantityPopup()
// 跳转到付款页面
uni.navigateTo({
url: `/pages/payment/purchase?order_id=${orderRes.data.order_id}&order_no=${orderRes.data.order_no}&is_second=${isSecond}`
})
uni.showToast({
title: '订单创建成功',
icon: 'success'
})
} else {
throw new Error(orderRes.message || '创建订单失败')
}
} catch (error) {
uni.hideLoading()
console.error('创建订单失败:', error)
uni.showToast({
title: error.message || '创建订单失败',
icon: 'none'
})
}
}
}
}
</script>
<style scoped>
.container {
background-color: #f5f5f5;
min-height: 100vh;
padding-bottom: 120rpx;
}
.image-section {
position: relative;
background: white;
}
.image-swiper {
width: 100%;
height: 750rpx;
}
.product-image {
width: 100%;
height: 100%;
}
.image-count {
position: absolute;
bottom: 20rpx;
right: 20rpx;
background: rgba(0, 0, 0, 0.5);
color: white;
padding: 10rpx 20rpx;
border-radius: 20rpx;
font-size: 24rpx;
}
.product-info-section {
background: white;
padding: 30rpx;
margin-bottom: 20rpx;
}
.price-section {
display: flex;
align-items: baseline;
margin-bottom: 20rpx;
}
.current-price {
display: flex;
align-items: baseline;
margin-right: 20rpx;
}
.price-symbol {
font-size: 28rpx;
color: #FF4444;
font-weight: bold;
}
.price-value {
font-size: 48rpx;
color: #FF4444;
font-weight: bold;
}
.original-price {
display: flex;
align-items: center;
}
.original-price-text {
font-size: 24rpx;
color: #999;
text-decoration: line-through;
}
.product-title {
margin-bottom: 20rpx;
}
.product-name {
font-size: 32rpx;
color: #333;
font-weight: bold;
line-height: 1.4;
}
.product-stats {
display: flex;
gap: 30rpx;
}
.stats-item {
font-size: 26rpx;
color: #666;
}
.seller-section {
background: white;
padding: 30rpx;
margin-bottom: 20rpx;
}
.section-title {
font-size: 30rpx;
font-weight: bold;
color: #333;
margin-bottom: 20rpx;
}
.seller-info {
display: flex;
align-items: center;
}
.seller-avatar {
width: 80rpx;
height: 80rpx;
border-radius: 40rpx;
margin-right: 20rpx;
}
.seller-avatar-placeholder {
width: 80rpx;
height: 80rpx;
border-radius: 40rpx;
background: #f5f5f5;
display: flex;
align-items: center;
justify-content: center;
margin-right: 20rpx;
}
.seller-details {
flex: 1;
}
.seller-name {
font-size: 28rpx;
color: #333;
font-weight: bold;
display: block;
margin-bottom: 8rpx;
}
.seller-code {
font-size: 24rpx;
color: #666;
}
.description-section {
background: white;
padding: 30rpx;
margin-bottom: 20rpx;
}
.description-content {
margin-top: 20rpx;
}
.description-text {
font-size: 28rpx;
color: #666;
line-height: 1.6;
}
.bottom-bar {
position: fixed;
bottom: 0;
left: 0;
right: 0;
background: white;
padding: 20rpx 30rpx;
box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
}
.buy-btn {
width: 100%;
height: 80rpx;
background: linear-gradient(135deg, #FF4444 0%, #FF6666 100%);
border: none;
border-radius: 40rpx;
color: white;
font-size: 32rpx;
font-weight: bold;
display: flex;
align-items: center;
justify-content: center;
}
.buy-btn:disabled {
background: #ccc;
}
.quantity-popup {
display: flex;
flex-direction: column;
max-height: 75vh;
background: white;
border-radius: 20rpx 20rpx 0 0;
}
.popup-content {
flex: 1;
padding: 40rpx 30rpx 20rpx;
overflow-y: auto;
}
.popup-footer {
padding: 20rpx 30rpx;
padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
border-top: 1rpx solid #f5f5f5;
background: white;
}
.popup-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30rpx;
}
.popup-title {
font-size: 32rpx;
font-weight: bold;
color: #333;
}
.close-btn {
padding: 10rpx;
}
.popup-product-info {
display: flex;
align-items: center;
padding: 20rpx;
background: #f8f8f8;
border-radius: 20rpx;
margin-bottom: 40rpx;
}
.popup-product-image {
width: 120rpx;
height: 120rpx;
border-radius: 10rpx;
margin-right: 20rpx;
}
.popup-product-details {
flex: 1;
}
.popup-product-name {
font-size: 28rpx;
color: #333;
font-weight: bold;
display: block;
margin-bottom: 10rpx;
}
.popup-product-price {
font-size: 32rpx;
color: #FF4444;
font-weight: bold;
}
.quantity-selector {
margin-bottom: 40rpx;
}
.quantity-label {
font-size: 28rpx;
color: #333;
display: block;
margin-bottom: 20rpx;
}
.quantity-controls {
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 10rpx;
}
.quantity-btn {
width: 60rpx;
height: 60rpx;
border: 1rpx solid #ddd;
border-radius: 10rpx;
display: flex;
align-items: center;
justify-content: center;
background: white;
}
.quantity-btn.disabled {
background: #f5f5f5;
border-color: #eee;
}
.quantity-input {
width: 120rpx;
height: 60rpx;
text-align: center;
border: 1rpx solid #ddd;
border-left: none;
border-right: none;
font-size: 28rpx;
color: #333;
background: white;
}
.stock-info {
font-size: 24rpx;
color: #999;
text-align: center;
display: block;
}
.total-price {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 0;
}
.total-label {
font-size: 28rpx;
color: #333;
}
.total-amount {
font-size: 36rpx;
color: #FF4444;
font-weight: bold;
}
.confirm-buy-btn {
width: 100%;
height: 80rpx;
background: linear-gradient(135deg, #FF4444 0%, #FF6666 100%);
border: none;
border-radius: 40rpx;
color: white;
font-size: 32rpx;
font-weight: bold;
display: flex;
align-items: center;
justify-content: center;
margin: 0;
}
.confirm-buy-btn:disabled {
background: #ccc;
}
.loading-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(255, 255, 255, 0.8);
display: flex;
align-items: center;
justify-content: center;
z-index: 1000;
}
.loading-text {
font-size: 28rpx;
color: #666;
}
</style>
+703
View File
@@ -0,0 +1,703 @@
<template>
<view class="container">
<view class="header">
<view class="nav-bar">
<text class="nav-title">编辑个人信息</text>
<view class="nav-right" @click="saveProfile">
<text class="save-btn">保存</text>
</view>
</view>
</view>
<view class="content">
<!-- 头像上传 -->
<view class="form-item">
<text class="label">头像</text>
<view class="avatar-upload" @click="chooseAvatar">
<image v-if="userForm.avatar" class="avatar-preview" :src="getFullImageUrl(userForm.avatar)" mode="aspectFill"></image>
<view v-else class="avatar-placeholder">
<uni-icons type="camera" size="40" color="#999"></uni-icons>
</view>
</view>
</view>
<!-- 手机号 -->
<view class="form-item">
<text class="label">手机号</text>
<input class="input" v-model="userForm.phone" placeholder="请输入手机号" maxlength="11" />
</view>
<!-- 客户姓名 -->
<view class="form-item">
<text class="label">客户姓名</text>
<input class="input" v-model="userForm.customer_name" placeholder="请输入客户姓名" />
</view>
<!-- 真实姓名 -->
<view class="form-item">
<text class="label">真实姓名</text>
<input class="input" v-model="userForm.real_name" placeholder="请输入真实姓名" />
</view>
<!-- 公司名称 -->
<view class="form-item">
<text class="label">公司名称</text>
<input class="input" v-model="userForm.company_name" placeholder="请输入公司名称" />
</view>
<!-- 个人介绍 -->
<view class="form-item">
<text class="label">个人介绍</text>
<textarea class="textarea" v-model="userForm.personal_intro" placeholder="请输入个人介绍" maxlength="200"></textarea>
</view>
<!-- 修改密码 -->
<view class="password-section">
<text class="section-title">修改密码</text>
<view class="form-item">
<text class="label">当前密码</text>
<input class="input" v-model="passwordForm.current_password" type="password" placeholder="请输入当前密码" />
</view>
<view class="form-item">
<text class="label">新密码</text>
<input class="input" v-model="passwordForm.new_password" type="password" placeholder="请输入新密码" />
</view>
<view class="form-item">
<text class="label">确认新密码</text>
<input class="input" v-model="passwordForm.confirm_password" type="password" placeholder="请再次输入新密码" />
</view>
<view class="password-actions">
<button class="password-btn" @click="changePassword" :disabled="passwordLoading">
{{ passwordLoading ? '修改中...' : '修改密码' }}
</button>
</view>
</view>
<!-- 证件照片上传区域 -->
<!-- <view class="upload-section">
<text class="section-title">证件照片</text>
<view class="upload-item">
<text class="upload-label">营业执照</text>
<view class="image-upload" @click="chooseBusinessLicense">
<image v-if="userForm.business_license" class="upload-preview" :src="getFullImageUrl(userForm.business_license)" mode="aspectFill"></image>
<view v-else class="upload-placeholder">
<uni-icons type="camera" size="30" color="#999"></uni-icons>
<text class="upload-text">上传营业执照</text>
</view>
</view>
</view>
<view class="upload-item">
<text class="upload-label">身份证正面</text>
<view class="image-upload" @click="chooseIDCardFront">
<image v-if="userForm.id_card_front" class="upload-preview" :src="getFullImageUrl(userForm.id_card_front)" mode="aspectFill"></image>
<view v-else class="upload-placeholder">
<uni-icons type="camera" size="30" color="#999"></uni-icons>
<text class="upload-text">上传身份证正面</text>
</view>
</view>
</view>
<view class="upload-item">
<text class="upload-label">身份证反面</text>
<view class="image-upload" @click="chooseIDCardBack">
<image v-if="userForm.id_card_back" class="upload-preview" :src="getFullImageUrl(userForm.id_card_back)" mode="aspectFill"></image>
<view v-else class="upload-placeholder">
<uni-icons type="camera" size="30" color="#999"></uni-icons>
<text class="upload-text">上传身份证反面</text>
</view>
</view>
</view>
</view> -->
<!-- 收款码上传区域 -->
<!-- <view class="upload-section">
<text class="section-title">收款二维码</text>
<view class="upload-item">
<text class="upload-label">主收款码</text>
<view class="image-upload" @click="chooseMainPayment">
<image v-if="userForm.main_payment_qr_image" class="upload-preview" :src="getFullImageUrl(userForm.main_payment_qr_image)" mode="aspectFill"></image>
<view v-else class="upload-placeholder">
<uni-icons type="camera" size="30" color="#999"></uni-icons>
<text class="upload-text">上传主收款码</text>
</view>
</view>
</view>
<view class="upload-item">
<text class="upload-label">副收款码</text>
<view class="image-upload" @click="chooseSubPayment">
<image v-if="userForm.sub_payment_qr_image" class="upload-preview" :src="getFullImageUrl(userForm.sub_payment_qr_image)" mode="aspectFill"></image>
<view v-else class="upload-placeholder">
<uni-icons type="camera" size="30" color="#999"></uni-icons>
<text class="upload-text">上传副收款码</text>
</view>
</view>
</view>
</view> -->
</view>
</view>
</template>
<script>
import request from '@/utils/request.js'
export default {
data() {
return {
userForm: {
phone: '',
customer_name: '',
real_name: '',
avatar: '',
company_name: '',
personal_intro: '',
business_license: '',
id_card_front: '',
id_card_back: '',
main_payment_qr_image: '',
sub_payment_qr_image: ''
},
passwordForm: {
current_password: '',
new_password: '',
confirm_password: ''
},
loading: false,
passwordLoading: false
}
},
onLoad() {
this.loadUserInfo()
},
methods: {
// 获取完整的图片URL
getFullImageUrl(url) {
return request.getImageUrl(url)
},
// 加载用户信息
async loadUserInfo() {
try {
const res = await request.get('/back/current-user')
if (res.success) {
const user = res.data
this.userForm = {
phone: user.phone || '',
customer_name: user.customer_name || '',
real_name: user.real_name || '',
avatar: user.avatar || '',
company_name: user.company_name || '',
personal_intro: user.personal_intro || '',
business_license: user.business_license_image || '',
id_card_front: user.id_card_front_image || '',
id_card_back: user.id_card_back_image || '',
main_payment_qr_image: user.main_payment_qr_image || '',
sub_payment_qr_image: user.sub_payment_qr_image || ''
}
}
} catch (error) {
console.error('获取用户信息失败:', error)
uni.showToast({
title: '加载用户信息失败',
icon: 'none'
})
}
},
// 返回上一页
goBack() {
uni.navigateBack()
},
// 保存个人信息
async saveProfile() {
// 表单验证
if (!this.userForm.customer_name) {
uni.showToast({
title: '请输入客户姓名',
icon: 'none'
})
return
}
if (!this.userForm.real_name) {
uni.showToast({
title: '请输入真实姓名',
icon: 'none'
})
return
}
if (!this.userForm.phone) {
uni.showToast({
title: '请输入手机号',
icon: 'none'
})
return
}
// 手机号格式验证
const phoneRegex = /^1[3-9]\d{9}$/
if (!phoneRegex.test(this.userForm.phone)) {
uni.showToast({
title: '请输入正确的手机号',
icon: 'none'
})
return
}
this.loading = true
try {
const updateData = {
phone: this.userForm.phone,
customer_name: this.userForm.customer_name,
real_name: this.userForm.real_name,
avatar: this.userForm.avatar,
company_name: this.userForm.company_name,
personal_intro: this.userForm.personal_intro,
business_license: this.userForm.business_license,
id_card_front: this.userForm.id_card_front,
id_card_back: this.userForm.id_card_back,
main_payment_code: this.userForm.main_payment_qr_image,
backup_payment_code: this.userForm.sub_payment_qr_image
}
const res = await request.put('/back/update-profile', updateData)
if (res.success) {
uni.showToast({
title: '保存成功',
icon: 'success'
})
// 更新本地存储中的用户信息
uni.setStorageSync('userInfo', res.data)
// 延迟返回,让用户看到成功提示
setTimeout(() => {
uni.switchTab({
url:"/pages/profile/profile"
})
}, 500)
} else {
uni.showToast({
title: res.message || '保存失败',
icon: 'none'
})
}
} catch (error) {
console.error('保存个人信息失败:', error)
uni.showToast({
title: '保存失败',
icon: 'none'
})
} finally {
this.loading = false
}
},
// 上传图片的通用方法
async uploadImage(tempFilePath) {
try {
const uploadRes = await request.upload('/back/upload', tempFilePath)
if (uploadRes.success) {
return uploadRes.data.url
} else {
throw new Error(uploadRes.message || '上传失败')
}
} catch (error) {
console.error('上传图片失败:', error)
uni.showToast({
title: '上传失败',
icon: 'none'
})
return null
}
},
// 选择头像
chooseAvatar() {
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: async (res) => {
const tempFilePath = res.tempFilePaths[0]
const url = await this.uploadImage(tempFilePath)
if (url) {
this.userForm.avatar = url
}
}
})
},
// 选择营业执照
chooseBusinessLicense() {
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: async (res) => {
const tempFilePath = res.tempFilePaths[0]
const url = await this.uploadImage(tempFilePath)
if (url) {
this.userForm.business_license = url
}
}
})
},
// 选择身份证正面
chooseIDCardFront() {
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: async (res) => {
const tempFilePath = res.tempFilePaths[0]
const url = await this.uploadImage(tempFilePath)
if (url) {
this.userForm.id_card_front = url
}
}
})
},
// 选择身份证反面
chooseIDCardBack() {
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: async (res) => {
const tempFilePath = res.tempFilePaths[0]
const url = await this.uploadImage(tempFilePath)
if (url) {
this.userForm.id_card_back = url
}
}
})
},
// 选择主收款码
chooseMainPayment() {
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: async (res) => {
const tempFilePath = res.tempFilePaths[0]
const url = await this.uploadImage(tempFilePath)
if (url) {
this.userForm.main_payment_qr_image = url
}
}
})
},
// 选择副收款码
chooseSubPayment() {
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['album', 'camera'],
success: async (res) => {
const tempFilePath = res.tempFilePaths[0]
const url = await this.uploadImage(tempFilePath)
if (url) {
this.userForm.sub_payment_qr_image = url
}
}
})
},
// 修改密码
async changePassword() {
// 表单验证
if (!this.passwordForm.current_password) {
uni.showToast({
title: '请输入当前密码',
icon: 'none'
})
return
}
if (!this.passwordForm.new_password) {
uni.showToast({
title: '请输入新密码',
icon: 'none'
})
return
}
if (this.passwordForm.new_password.length < 6) {
uni.showToast({
title: '新密码至少6位',
icon: 'none'
})
return
}
if (this.passwordForm.new_password !== this.passwordForm.confirm_password) {
uni.showToast({
title: '两次输入的密码不一致',
icon: 'none'
})
return
}
if (this.passwordForm.current_password === this.passwordForm.new_password) {
uni.showToast({
title: '新密码不能与当前密码相同',
icon: 'none'
})
return
}
this.passwordLoading = true
try {
const passwordData = {
current_password: this.passwordForm.current_password,
new_password: this.passwordForm.new_password
}
const res = await request.put('/back/change-password', passwordData)
if (res.success) {
uni.showToast({
title: '密码修改成功',
icon: 'success'
})
// 清空密码表单
this.passwordForm = {
current_password: '',
new_password: '',
confirm_password: ''
}
} else {
uni.showToast({
title: res.message || '密码修改失败',
icon: 'none'
})
}
} catch (error) {
console.error('修改密码失败:', error)
uni.showToast({
title: '密码修改失败',
icon: 'none'
})
} finally {
this.passwordLoading = false
}
}
}
}
</script>
<style scoped>
.container {
background-color: #f5f5f5;
min-height: 100vh;
}
.header {
position: sticky;
top: 0;
background-color: #fff;
z-index: 100;
}
.nav-bar {
display: flex;
align-items: center;
justify-content: space-between;
padding: 20rpx 30rpx;
border-bottom: 1rpx solid #eee;
}
.nav-left {
width: 80rpx;
}
.nav-title {
font-size: 36rpx;
font-weight: bold;
color: #333;
}
.nav-right {
width: 80rpx;
text-align: right;
}
.save-btn {
color: #FF4444;
font-size: 32rpx;
}
.content {
padding: 0 30rpx;
}
.form-item {
background-color: #fff;
margin: 20rpx 0;
padding: 30rpx;
border-radius: 16rpx;
display: flex;
align-items: center;
}
.label {
font-size: 32rpx;
color: #333;
width: 200rpx;
flex-shrink: 0;
}
.input {
flex: 1;
font-size: 32rpx;
color: #333;
padding: 0 20rpx;
}
.textarea {
flex: 1;
font-size: 32rpx;
color: #333;
padding: 20rpx;
min-height: 120rpx;
border: 1rpx solid #eee;
border-radius: 8rpx;
}
.avatar-upload {
flex: 1;
display: flex;
justify-content: flex-end;
}
.avatar-preview {
width: 120rpx;
height: 120rpx;
border-radius: 60rpx;
}
.avatar-placeholder {
width: 120rpx;
height: 120rpx;
border-radius: 60rpx;
border: 2rpx dashed #ddd;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.placeholder-text {
font-size: 24rpx;
color: #999;
margin-top: 10rpx;
}
.upload-section {
background-color: #fff;
margin: 40rpx 0;
padding: 30rpx;
border-radius: 16rpx;
}
.section-title {
font-size: 36rpx;
font-weight: bold;
color: #333;
margin-bottom: 30rpx;
display: block;
}
.upload-item {
display: flex;
align-items: center;
margin-bottom: 30rpx;
}
.upload-item:last-child {
margin-bottom: 0;
}
.upload-label {
font-size: 32rpx;
color: #333;
width: 200rpx;
flex-shrink: 0;
}
.image-upload {
flex: 1;
display: flex;
justify-content: flex-end;
}
.upload-preview {
width: 200rpx;
height: 150rpx;
border-radius: 8rpx;
}
.upload-placeholder {
width: 200rpx;
height: 150rpx;
border: 2rpx dashed #ddd;
border-radius: 8rpx;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.upload-text {
font-size: 24rpx;
color: #999;
margin-top: 10rpx;
}
.password-section {
background-color: #fff;
margin: 40rpx 0;
padding: 30rpx;
border-radius: 16rpx;
}
.password-actions {
margin-top: 30rpx;
text-align: center;
}
.password-btn {
background-color: #FF4444;
color: white;
border: none;
border-radius: 50rpx;
font-size: 32rpx;
min-width: 200rpx;
}
.password-btn:disabled {
background-color: #ccc;
color: #999;
}
</style>
+490
View File
@@ -0,0 +1,490 @@
<template>
<view class="container">
<!-- 用户信息头部 -->
<view class="user-header">
<view class="user-info">
<view class="avatar-container">
<view class="avatar" v-if="userInfo.avatar">
<image class="avatar-image" :src="getFullImageUrl(userInfo.avatar)" mode="aspectFill"></image>
</view>
<view class="avatar default-avatar" v-else>
<uni-icons type="person-filled" size="60" color="#fff"></uni-icons>
</view>
</view>
<view class="user-details" @click="goToEditProfile">
<text class="user-name">{{ userInfo.customer_name || '未设置姓名' }}</text>
<text class="user-phone">{{ userInfo.phone }}</text>
<view class="user-points" @click.stop="goToScores">
<text class="points-text">积分:{{ userInfo.current_points || 0 }}</text>
<uni-icons type="right" size="16" color="#fff"></uni-icons>
</view>
</view>
<view class="edit-btn" @click="goToEditProfile">
<uni-icons type="compose" size="24" color="#fff"></uni-icons>
</view>
</view>
</view>
<!-- 我的买单 -->
<view class="order-section">
<view class="section-header">
<text class="section-title">我的买单</text>
<text class="view-all" @click="viewAllOrders('purchase')">查看全部></text>
</view>
<view class="order-status-bar">
<view class="status-item" @click="goToOrders('purchase', 'pending')">
<uni-icons type="wallet" size="32" color="#FF8800"></uni-icons>
<text class="status-text">待付款</text>
<view class="status-badge" v-if="pendingCount > 0">{{ pendingCount }}</view>
</view>
<view class="status-item" @click="goToOrders('purchase', 'confirming')">
<uni-icons type="checkmarkempty" size="32" color="#1890FF"></uni-icons>
<text class="status-text">待确认</text>
<view class="status-badge" v-if="confirmingCount > 0">{{ confirmingCount }}</view>
</view>
<view class="status-item" @click="goToOrders('purchase', 'completed')">
<uni-icons type="checkbox" size="32" color="#52C41A"></uni-icons>
<text class="status-text">已完成</text>
</view>
</view>
</view>
<!-- 我的卖单 -->
<view class="order-section">
<view class="section-header">
<text class="section-title">我的卖单</text>
<text class="view-all" @click="viewAllOrders('sales')">查看全部></text>
</view>
<view class="order-status-bar">
<view class="status-item" @click="goToOrders('sales', 'pending')">
<uni-icons type="shop" size="32" color="#FF8800"></uni-icons>
<text class="status-text">待付款</text>
<view class="status-badge" v-if="salesPendingCount > 0">{{ salesPendingCount }}</view>
</view>
<view class="status-item" @click="goToOrders('sales', 'confirming')">
<uni-icons type="eye" size="32" color="#1890FF"></uni-icons>
<text class="status-text">待确认</text>
<view class="status-badge" v-if="salesConfirmingCount > 0">{{ salesConfirmingCount }}</view>
</view>
<view class="status-item" @click="goToOrders('sales', 'completed')">
<uni-icons type="checkmarkempty" size="32" color="#52C41A"></uni-icons>
<text class="status-text">已完成</text>
</view>
</view>
</view>
<!-- 其他服务 -->
<view class="service-section">
<view class="section-title">其他服务</view>
<view class="service-grid">
<view class="service-item" @click="goToWarehouse">
<uni-icons type="home" size="32" color="#666"></uni-icons>
<text class="service-text">我的仓库</text>
</view>
<view class="service-item" @click="goToScores">
<uni-icons type="medal" size="32" color="#666"></uni-icons>
<text class="service-text">积分明细</text>
</view>
<view class="service-item" @click="goToReconciliation">
<uni-icons type="bars" size="32" color="#666"></uni-icons>
<text class="service-text">对账管理</text>
</view>
<view class="service-item" @click="goToPayment">
<uni-icons type="wallet" size="32" color="#666"></uni-icons>
<text class="service-text">收款方式</text>
</view>
<view class="service-item" @click="goToService">
<uni-icons type="chatbubble" size="32" color="#666"></uni-icons>
<text class="service-text">联系客服</text>
</view>
</view>
</view>
<!-- 底部功能 -->
<view class="bottom-section">
<view class="bottom-item" @click="goToAddress">
<uni-icons type="location" size="32" color="#666"></uni-icons>
<text class="bottom-text">收货地址</text>
</view>
<view class="bottom-item" @click="logout">
<uni-icons type="loop" size="32" color="#666"></uni-icons>
<text class="bottom-text">退出登录</text>
</view>
</view>
</view>
</template>
<script>
import request from '@/utils/request.js'
export default {
data() {
return {
userInfo: {},
confirmingCount: 0,
salesConfirmingCount: 0,
pendingCount: 0,
salesPendingCount: 0,
phone:''
}
},
onReady() {
// 从本地存储获取用户信息
this.userInfo = uni.getStorageSync('userInfo') || {}
},
onLoad() {
this.loadUserInfo()
this.loadOrderStats()
this.loadPhone()
},
onShow() {
this.loadUserInfo()
this.loadOrderStats()
this.loadPhone()
},
methods: {
// 获取完整的图片URL
getFullImageUrl(url) {
return request.getImageUrl(url)
},
async loadPhone(){
const res= await request.get("/back/config",{key:"phone"})
if(res.success) this.phone=res.data
},
// 加载用户信息
async loadUserInfo() {
try {
const res = await request.get('/back/current-user')
if (res.success) {
this.userInfo = res.data
// 更新本地存储中的用户信息
uni.setStorageSync('userInfo', res.data)
}
} catch (error) {
console.error('获取用户信息失败:', error)
}
},
// 加载订单统计
async loadOrderStats() {
try {
const res = await request.get('/back/user/orders/stats')
if (res.success) {
this.pendingCount = res.data.purchase_pending_count || 0
this.confirmingCount = res.data.purchase_confirming_count || 0
this.salesPendingCount = res.data.sales_pending_count || 0
this.salesConfirmingCount = res.data.sales_confirming_count || 0
}
} catch (error) {
console.error('获取订单统计失败:', error)
}
},
// 跳转到个人信息编辑页面
goToEditProfile() {
uni.navigateTo({
url: '/pages/profile/edit'
})
},
// 跳转到订单页面
goToOrders(type, status) {
const url = type === 'purchase' ? '/pages/orders/orders' : '/pages/sales/sales'
uni.navigateTo({
url: `${url}?status=${status}`
})
},
// 查看全部订单
viewAllOrders(type) {
const url = type === 'purchase' ? '/pages/orders/orders' : '/pages/sales/sales'
uni.navigateTo({
url: url
})
},
// 跳转到仓库
goToWarehouse() {
uni.navigateTo({
url: '/pages/warehouse/warehouse'
})
},
// 跳转到积分明细
goToScores() {
uni.navigateTo({
url: '/pages/scores/scores'
})
},
// 跳转到对账管理
goToReconciliation() {
uni.navigateTo({
url: '/pages/reconciliation/reconciliation'
})
},
// 跳转到收款方式
goToPayment() {
uni.navigateTo({
url: '/pages/payment/payment'
})
},
// 联系客服
goToService() {
uni.showModal({
title: '联系客服',
content: '请在服务群内联系客服',
showCancel: false,
})
// const res = uni.getSystemInfoSync();
// const phone=""+this.phone
// // ios系统默认有个模态框
// if (res.platform == 'ios') {
// uni.makePhoneCall({
// phoneNumber: phone,
// })
// } else {
// //安卓手机手动设置一个showActionSheet
// uni.showActionSheet({
// itemList: ['phone', '呼叫'],
// success: function(res) {
// if (res.tapIndex == 1) {
// uni.makePhoneCall({
// phoneNumber: phone,
// })
// }
// }
// })
// }
},
// 跳转到收货地址
goToAddress() {
uni.navigateTo({
url: '/pages/address/address'
})
},
// 退出登录
logout() {
uni.showModal({
title: '确认退出',
content: '确定要退出登录吗?',
success: (res) => {
if (res.confirm) {
// 清除本地存储
uni.removeStorageSync('token')
uni.removeStorageSync('userInfo')
uni.reLaunch({
url: '/pages/login/login'
})
}
}
})
}
}
}
</script>
<style scoped>
.container {
background-color: #f5f5f5;
min-height: 100vh;
}
/* 用户信息头部 */
.user-header {
background: linear-gradient(135deg, #FF4444 0%, #FF6666 100%);
padding: 40rpx 30rpx;
color: #fff;
}
.user-info {
display: flex;
align-items: center;
}
.avatar-container {
margin-right: 30rpx;
}
.avatar {
width: 120rpx;
height: 120rpx;
border-radius: 50%;
border: 4rpx solid rgba(255, 255, 255, 0.3);
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
.avatar-image {
width: 100%;
height: 100%;
}
.default-avatar {
background-color: rgba(255, 255, 255, 0.2);
}
.user-details {
flex: 1;
}
.user-name {
display: block;
font-size: 36rpx;
font-weight: bold;
margin-bottom: 10rpx;
}
.user-phone {
display: block;
font-size: 28rpx;
opacity: 0.9;
margin-bottom: 10rpx;
}
.user-points {
font-size: 28rpx;
opacity: 0.9;
display: flex;
align-items: center;
background-color: rgba(255, 255, 255, 0.1);
border-radius: 20rpx;
padding: 8rpx 15rpx;
margin-top: 10rpx;
max-width: 200rpx;
}
.points-text {
margin-right: 8rpx;
}
.edit-btn {
padding: 20rpx;
}
/* 订单区域 */
.order-section {
background-color: #fff;
margin: 20rpx;
border-radius: 16rpx;
padding: 30rpx;
}
.section-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30rpx;
}
.section-title {
font-size: 32rpx;
font-weight: bold;
color: #333;
}
.view-all {
font-size: 24rpx;
color: #999;
}
.order-status-bar {
display: flex;
justify-content: space-around;
}
.status-item {
display: flex;
flex-direction: column;
align-items: center;
position: relative;
}
.status-item uni-icons {
margin-bottom: 15rpx;
}
.status-text {
font-size: 24rpx;
color: #666;
}
.status-badge {
position: absolute;
top: -5rpx;
right: -5rpx;
background-color: #FF4444;
color: #fff;
font-size: 20rpx;
padding: 4rpx 8rpx;
border-radius: 20rpx;
min-width: 32rpx;
text-align: center;
}
/* 服务区域 */
.service-section {
background-color: #fff;
margin: 20rpx;
border-radius: 16rpx;
padding: 30rpx;
}
.service-grid {
display: flex;
justify-content: space-around;
margin-top: 30rpx;
}
.service-item {
display: flex;
flex-direction: column;
align-items: center;
}
.service-item uni-icons {
margin-bottom: 15rpx;
}
.service-text {
font-size: 24rpx;
color: #666;
}
/* 底部区域 */
.bottom-section {
display: flex;
margin: 20rpx;
gap: 20rpx;
}
.bottom-item {
flex: 1;
background-color: #fff;
border-radius: 16rpx;
padding: 40rpx 30rpx;
display: flex;
flex-direction: column;
align-items: center;
}
.bottom-item uni-icons {
margin-bottom: 15rpx;
}
.bottom-text {
font-size: 24rpx;
color: #666;
}
</style>
@@ -0,0 +1,581 @@
<template>
<view class="reconciliation-container">
<!-- 日期选择区域 -->
<view class="date-selector">
<view class="date-row">
<view class="date-item">
<text class="date-label">开始日期</text>
<view class="date-picker" @click="showStartDatePicker">
<text class="date-text">{{ startDate }}</text>
</view>
</view>
<view class="date-item">
<text class="date-label">结束日期</text>
<view class="date-picker" @click="showEndDatePicker">
<text class="date-text">{{ endDate }}</text>
</view>
</view>
<view class="date-item">
<text class="date-label blue">按日期筛选</text>
<view class="refresh-btn" @click="refreshData">
<text class="refresh-text">重置</text>
</view>
</view>
</view>
</view>
<!-- 一级市场统计 -->
<view class="stats-section">
<view class="stats-title green">一级市场已确认</view>
<view class="stats-row">
<view class="stats-item">
<text class="stats-label">金额:</text>
<text class="stats-value">{{ primaryConfirmed.amount }}</text>
</view>
<view class="stats-item">
<text class="stats-label">数量:</text>
<text class="stats-value">{{ primaryConfirmed.quantity }}</text>
</view>
</view>
</view>
<view class="stats-section">
<view class="stats-title red">一级市场待确认</view>
<view class="stats-row">
<view class="stats-item">
<text class="stats-label">金额:</text>
<text class="stats-value">{{ primaryPending.amount }}</text>
</view>
<view class="stats-item">
<text class="stats-label">数量:</text>
<text class="stats-value">{{ primaryPending.quantity }}</text>
</view>
</view>
</view>
<!-- 二级市场买单统计 -->
<view class="stats-section">
<view class="stats-title green">二级市场买单已确认</view>
<view class="stats-row">
<view class="stats-item">
<text class="stats-label">金额:</text>
<text class="stats-value">{{ secondaryBuyConfirmed.amount }}</text>
</view>
<view class="stats-item">
<text class="stats-label">数量:</text>
<text class="stats-value">{{ secondaryBuyConfirmed.quantity }}</text>
</view>
</view>
</view>
<view class="stats-section">
<view class="stats-title red">二级市场买单待确认</view>
<view class="stats-row">
<view class="stats-item">
<text class="stats-label">金额:</text>
<text class="stats-value">{{ secondaryBuyPending.amount }}</text>
</view>
<view class="stats-item">
<text class="stats-label">数量:</text>
<text class="stats-value">{{ secondaryBuyPending.quantity }}</text>
</view>
</view>
</view>
<!-- 二级市场卖单统计 -->
<view class="stats-section">
<view class="stats-title green">二级市场卖单已确认</view>
<view class="stats-row">
<view class="stats-item">
<text class="stats-label">金额:</text>
<text class="stats-value">{{ secondarySellConfirmed.amount }}</text>
</view>
<view class="stats-item">
<text class="stats-label">数量:</text>
<text class="stats-value">{{ secondarySellConfirmed.quantity }}</text>
</view>
</view>
</view>
<view class="stats-section">
<view class="stats-title red">二级市场卖单待确认</view>
<view class="stats-row">
<view class="stats-item">
<text class="stats-label">金额:</text>
<text class="stats-value">{{ secondarySellPending.amount }}</text>
</view>
<view class="stats-item">
<text class="stats-label">数量:</text>
<text class="stats-value">{{ secondarySellPending.quantity }}</text>
</view>
</view>
</view>
<!-- 仓库商品统计 -->
<view class="warehouse-section">
<view class="warehouse-title red">仓库商品不参与日期筛选</view>
<view class="warehouse-row">
<view class="warehouse-item">
<view class="warehouse-status green">寄售中</view>
<view class="warehouse-stats">
<text class="stats-label">金额:</text>
<text class="stats-value">{{ warehouseActive.amount }}</text>
</view>
<view class="warehouse-stats">
<text class="stats-label">数量:</text>
<text class="stats-value">{{ warehouseActive.quantity }}</text>
</view>
</view>
<view class="warehouse-item">
<view class="warehouse-status gray">未寄售</view>
<view class="warehouse-stats">
<text class="stats-label">金额:</text>
<text class="stats-value">{{ warehouseInactive.amount }}</text>
</view>
<view class="warehouse-stats">
<text class="stats-label">数量:</text>
<text class="stats-value">{{ warehouseInactive.quantity }}</text>
</view>
</view>
</view>
</view>
<!-- 积分变更统计 -->
<view class="score-section">
<view class="score-left">
<view class="score-title">积分变更</view>
<view class="score-stats">
<text class="score-label">增加积分:</text>
<text class="score-value">{{ scoreChange.increase }}</text>
</view>
<view class="score-stats">
<text class="score-label">减少积分:</text>
<text class="score-value">{{ scoreChange.decrease }}</text>
</view>
</view>
<view class="score-right" @click="goToScoreDetail">
<view class="score-icon">📋</view>
<text class="score-link">积分变更记录</text>
</view>
</view>
<uni-datetime-picker
ref="startPicker"
type="date"
v-model="startDate"
@change="onStartDateChange"
:clear-icon="false"
/>
<uni-datetime-picker
ref="endPicker"
type="date"
v-model="endDate"
@change="onEndDateChange"
:clear-icon="false"
/>
</view>
</template>
<script>
import request from '@/utils/request.js'
export default {
name: 'Reconciliation',
data() {
return {
// 日期选择
startDate: '',
endDate: '',
// 一级市场统计
primaryConfirmed: {
amount: 0,
quantity: 0
},
primaryPending: {
amount: 0,
quantity: 0
},
// 二级市场买单统计
secondaryBuyConfirmed: {
amount: 0,
quantity: 0
},
secondaryBuyPending: {
amount: 0,
quantity: 0
},
// 二级市场卖单统计
secondarySellConfirmed: {
amount: 0,
quantity: 0
},
secondarySellPending: {
amount: 0,
quantity: 0
},
// 仓库商品统计
warehouseActive: {
amount: 0,
quantity: 0
},
warehouseInactive: {
amount: 0,
quantity: 0
},
// 积分变更统计
scoreChange: {
increase: 0,
decrease: 0
}
}
},
onLoad() {
this.initDates()
this.loadReconciliationData()
},
methods: {
// 初始化日期(默认今天)
initDates() {
const today = new Date()
const dateStr = today.getFullYear() + '-' +
String(today.getMonth() + 1).padStart(2, '0') + '-' +
String(today.getDate()).padStart(2, '0')
this.startDate = dateStr
this.endDate = dateStr
},
// 返回上一页
goBack() {
uni.navigateBack()
},
// 显示开始日期选择器
showStartDatePicker() {
this.$refs.startPicker.show()
},
// 显示结束日期选择器
showEndDatePicker() {
this.$refs.endPicker.show()
},
// 开始日期变更
onStartDateChange(e) {
this.startDate = e
this.loadReconciliationData()
},
// 结束日期变更
onEndDateChange(e) {
this.endDate = e
this.loadReconciliationData()
},
// 重置数据
refreshData() {
this.initDates()
this.loadReconciliationData()
},
// 加载对账数据
async loadReconciliationData() {
try {
uni.showLoading({
title: '加载中...'
})
const params = {
start_date: this.startDate,
end_date: this.endDate
}
const response = await request.get('/back/user/reconciliation/stats', params )
if (response.success) {
const data = response.data
// 一级市场统计
this.primaryConfirmed = data.primary_confirmed || { amount: 0, quantity: 0 }
this.primaryPending = data.primary_pending || { amount: 0, quantity: 0 }
// 二级市场买单统计
this.secondaryBuyConfirmed = data.secondary_buy_confirmed || { amount: 0, quantity: 0 }
this.secondaryBuyPending = data.secondary_buy_pending || { amount: 0, quantity: 0 }
// 二级市场卖单统计
this.secondarySellConfirmed = data.secondary_sell_confirmed || { amount: 0, quantity: 0 }
this.secondarySellPending = data.secondary_sell_pending || { amount: 0, quantity: 0 }
// 仓库商品统计
this.warehouseActive = data.warehouse_active || { amount: 0, quantity: 0 }
this.warehouseInactive = data.warehouse_inactive || { amount: 0, quantity: 0 }
// 积分变更统计
this.scoreChange = data.score_change || { increase: 0, decrease: 0 }
} else {
uni.showToast({
title: response.message || '加载失败',
icon: 'none'
})
}
} catch (error) {
console.error('加载对账数据失败:', error)
uni.showToast({
title: '网络错误',
icon: 'none'
})
} finally {
uni.hideLoading()
}
},
// 跳转到积分明细页面
goToScoreDetail() {
uni.navigateTo({
url: '/pages/scores/scores'
})
}
}
}
</script>
<style scoped>
.reconciliation-container {
min-height: 100vh;
background-color: #f5f5f5;
}
/* 导航栏 */
.nav-bar {
display: flex;
align-items: center;
justify-content: center;
height: 88rpx;
background: linear-gradient(135deg, #ff6b6b, #ff8e8e);
color: white;
position: relative;
}
.nav-back {
position: absolute;
left: 30rpx;
}
.nav-back-text {
font-size: 32rpx;
color: white;
}
.nav-title {
font-size: 36rpx;
font-weight: 600;
}
/* 日期选择区域 */
.date-selector {
background: white;
padding: 30rpx;
margin-bottom: 20rpx;
}
.date-row {
display: flex;
justify-content: space-between;
align-items: center;
}
.date-item {
text-align: center;
}
.date-label {
display: block;
font-size: 28rpx;
color: #333;
margin-bottom: 10rpx;
}
.date-label.blue {
color: #007aff;
}
.date-picker {
padding: 10rpx 20rpx;
border: 1rpx solid #ddd;
border-radius: 8rpx;
background: white;
}
.date-text {
font-size: 26rpx;
color: #333;
}
.refresh-btn {
padding: 10rpx 20rpx;
background: #007aff;
border-radius: 8rpx;
}
.refresh-text {
font-size: 26rpx;
color: white;
}
/* 统计区域 */
.stats-section {
background: white;
margin: 0 30rpx 20rpx;
padding: 30rpx;
border-radius: 12rpx;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}
.stats-title {
font-size: 32rpx;
font-weight: 600;
margin-bottom: 20rpx;
text-align: center;
}
.stats-title.green {
color: #52c41a;
}
.stats-title.red {
color: #ff4d4f;
}
.stats-row {
display: flex;
justify-content: space-around;
}
.stats-item {
text-align: center;
}
.stats-label {
font-size: 28rpx;
color: #666;
}
.stats-value {
font-size: 32rpx;
font-weight: 600;
color: #333;
margin-left: 10rpx;
}
/* 仓库商品区域 */
.warehouse-section {
background: white;
margin: 0 30rpx 20rpx;
padding: 30rpx;
border-radius: 12rpx;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}
.warehouse-title {
font-size: 32rpx;
font-weight: 600;
color: #ff4d4f;
text-align: center;
margin-bottom: 30rpx;
}
.warehouse-row {
display: flex;
justify-content: space-between;
}
.warehouse-item {
flex: 1;
text-align: center;
padding: 0 20rpx;
}
.warehouse-status {
font-size: 28rpx;
font-weight: 600;
margin-bottom: 15rpx;
}
.warehouse-status.green {
color: #52c41a;
}
.warehouse-status.gray {
color: #999;
}
.warehouse-stats {
margin-bottom: 10rpx;
}
/* 积分变更区域 */
.score-section {
background: white;
margin: 0 30rpx 40rpx;
padding: 30rpx;
border-radius: 12rpx;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
display: flex;
justify-content: space-between;
align-items: center;
}
.score-left {
flex: 1;
}
.score-title {
font-size: 32rpx;
font-weight: 600;
color: #333;
margin-bottom: 20rpx;
}
.score-stats {
margin-bottom: 10rpx;
}
.score-label {
font-size: 28rpx;
color: #666;
}
.score-value {
font-size: 32rpx;
font-weight: 600;
color: #333;
margin-left: 10rpx;
}
.score-right {
text-align: center;
padding: 20rpx;
}
.score-icon {
font-size: 60rpx;
margin-bottom: 10rpx;
}
.score-link {
font-size: 24rpx;
color: #007aff;
}
</style>
+669
View File
@@ -0,0 +1,669 @@
<template>
<view class="container">
<view class="register-header">
<text class="page-title">用户注册</text>
</view>
<view class="register-form">
<!-- 基本信息 -->
<view class="section-title">基本信息</view>
<view class="form-item">
<text class="form-label">手机号 *</text>
<input class="form-input"
v-model="registerForm.phone"
type="number"
placeholder="请输入手机号"
maxlength="11" />
</view>
<view class="form-item">
<text class="form-label">密码 *</text>
<input class="form-input"
v-model="registerForm.password"
type="password"
placeholder="请输入密码(6-20位)" />
</view>
<view class="form-item">
<text class="form-label">确认密码 *</text>
<input class="form-input"
v-model="registerForm.confirmPassword"
type="password"
placeholder="请再次输入密码" />
</view>
<view class="form-item">
<text class="form-label">店铺名称 *</text>
<input class="form-input"
v-model="registerForm.customer_name"
placeholder="请输入店铺名称" />
</view>
<view class="form-item">
<text class="form-label">法人名称 *</text>
<input class="form-input"
v-model="registerForm.real_name"
placeholder="请输入法人名称" />
</view>
<view class="form-item">
<text class="form-label">公司名称 *</text>
<input class="form-input"
v-model="registerForm.company_name"
placeholder="请输入公司名称" />
</view>
<!-- 证件上传 -->
<view class="section-title">证件信息</view>
<view class="upload-section">
<text class="upload-label">身份证正面 *</text>
<view class="upload-area" @click="chooseIdCardFront">
<image v-if="registerForm.id_card_front"
:src="getFullImageUrl(registerForm.id_card_front)"
mode="aspectFill"
class="upload-image"></image>
<view v-else class="upload-placeholder">
<uni-icons type="camera" size="30" color="#999"></uni-icons>
<text class="upload-text">点击上传身份证正面</text>
</view>
</view>
</view>
<view class="upload-section">
<text class="upload-label">身份证反面 *</text>
<view class="upload-area" @click="chooseIdCardBack">
<image v-if="registerForm.id_card_back"
:src="getFullImageUrl(registerForm.id_card_back)"
mode="aspectFill"
class="upload-image"></image>
<view v-else class="upload-placeholder">
<uni-icons type="camera" size="30" color="#999"></uni-icons>
<text class="upload-text">点击上传身份证反面</text>
</view>
</view>
</view>
<view class="upload-section">
<text class="upload-label">营业执照 *</text>
<view class="upload-area" @click="chooseBusinessLicense">
<image v-if="registerForm.business_license"
:src="getFullImageUrl(registerForm.business_license)"
mode="aspectFill"
class="upload-image"></image>
<view v-else class="upload-placeholder">
<uni-icons type="camera" size="30" color="#999"></uni-icons>
<text class="upload-text">点击上传营业执照</text>
</view>
</view>
</view>
<!-- 验证方式 -->
<view class="section-title">验证信息</view>
<!-- 短信验证码(必填) -->
<view class="verify-section">
<view class="form-item">
<text class="form-label">短信验证码 *</text>
<view class="verify-input-group">
<input class="form-input verify-input"
v-model="registerForm.sms_code"
type="number"
placeholder="请输入验证码"
maxlength="6" />
<button class="verify-btn"
@click="sendSmsCode"
:disabled="smsLoading || countdown > 0">
{{ smsLoading ? '发送中...' : countdown > 0 ? `${countdown}s` : '获取验证码' }}
</button>
</view>
</view>
</view>
<!-- 推荐人身份码(选填) -->
<view class="form-item">
<text class="form-label">推荐人身份码</text>
<input class="form-input"
v-model="registerForm.referrer_identity_code"
placeholder="请输入推荐人身份码(选填)" />
</view>
<!-- 用户协议 -->
<view class="agreement-section">
<view class="agreement-item" @click="toggleAgreement">
<uni-icons :type="agreed ? 'checkbox-filled' : 'circle'" size="16" :color="agreed ? '#FF4444' : '#999'"></uni-icons>
<text class="agreement-text">我已阅读并同意</text>
<text class="agreement-link">《用户协议》</text>
<text class="agreement-text">和</text>
<text class="agreement-link">《隐私政策》</text>
</view>
</view>
<!-- 注册按钮 -->
<button class="register-btn" @click="handleRegister" :disabled="registerLoading">
{{ registerLoading ? '注册中...' : '立即注册' }}
</button>
<view class="login-link">
<text class="link-text">已有账号?</text>
<text class="link-action" @click="goToLogin">立即登录</text>
</view>
</view>
</view>
</template>
<script>
import request from '@/utils/request.js'
export default {
data() {
return {
token:'',
registerForm: {
phone: '',
password: '',
confirmPassword: '',
customer_name: '',
real_name: '',
company_name: '',
id_card_front: '',
id_card_back: '',
business_license: '',
referrer_identity_code: '',
sms_code: ''
},
agreed: false,
registerLoading: false,
smsLoading: false,
countdown: 0
}
},
onLoad() {
this.token=uni.getStorageSync('token')
},
methods: {
// 获取完整的图片URL
getFullImageUrl(url) {
return request.getImageUrl(url)
},
// 选择身份证正面
chooseIdCardFront() {
this.chooseImage('id_card_front')
},
// 选择身份证反面
chooseIdCardBack() {
this.chooseImage('id_card_back')
},
// 选择营业执照
chooseBusinessLicense() {
this.chooseImage('business_license')
},
// 选择图片并上传
chooseImage(field) {
uni.chooseImage({
count: 1,
sizeType: ['compressed'],
sourceType: ['camera', 'album'],
success: (res) => {
const tempFilePath = res.tempFilePaths[0]
this.uploadImage(tempFilePath, field)
}
})
},
// 上传图片
async uploadImage(filePath, field) {
uni.showLoading({
title: '上传中...'
})
try {
const res = await request.upload("/back/upload", filePath, {
token: this.token
})
if (res.success) {
this.registerForm[field] = res.data.url
uni.showToast({
title: '上传成功',
icon: 'success'
})
} else {
uni.showToast({
title: res.message || '上传失败',
icon: 'none'
})
}
// uni.uploadFile({
// url: request.config.baseURL + '/back/upload',
// filePath: filePath,
// name: 'file',
// header: {
// 'token': token
// },
// success: (uploadRes) => {
// try {
// const result = JSON.parse(uploadRes.data)
// if (result.success) {
// this.registerForm[field] = result.data.url
// uni.showToast({
// title: '上传成功',
// icon: 'success'
// })
// } else {
// uni.showToast({
// title: result.message || '上传失败',
// icon: 'none'
// })
// }
// } catch (e) {
// uni.showToast({
// title: '上传失败',
// icon: 'none'
// })
// }
// },
// fail: (err) => {
// console.log(err)
// uni.showToast({
// title: '上传失败',
// icon: 'none'
// })
// },
// complete: () => {
// uni.hideLoading()
// }
// })
} catch (error) {
uni.hideLoading()
uni.showToast({
title: '上传失败',
icon: 'none'
})
console.log(error)
}
},
// 发送短信验证码
async sendSmsCode() {
if (!this.registerForm.phone) {
uni.showToast({
title: '请先输入手机号',
icon: 'none'
})
return
}
if (!/^1[3-9]\d{9}$/.test(this.registerForm.phone)) {
uni.showToast({
title: '手机号格式不正确',
icon: 'none'
})
return
}
this.smsLoading = true
try {
const res = await request.post('/back/auth/send-sms', {
phone: this.registerForm.phone
})
if (res.success) {
uni.showToast({
title: '验证码发送成功',
icon: 'success'
})
// 开始倒计时
this.startCountdown()
} else {
uni.showToast({
title: res.message || '发送失败',
icon: 'none'
})
}
} catch (error) {
uni.showToast({
title: '发送失败',
icon: 'none'
})
} finally {
this.smsLoading = false
}
},
// 开始倒计时
startCountdown() {
this.countdown = 60
const timer = setInterval(() => {
this.countdown--
if (this.countdown <= 0) {
clearInterval(timer)
}
}, 1000)
},
// 切换协议同意状态
toggleAgreement() {
this.agreed = !this.agreed
},
// 表单验证
validateForm() {
if (!this.registerForm.phone) {
uni.showToast({ title: '请输入手机号', icon: 'none' })
return false
}
if (!/^1[3-9]\d{9}$/.test(this.registerForm.phone)) {
uni.showToast({ title: '手机号格式不正确', icon: 'none' })
return false
}
if (!this.registerForm.password) {
uni.showToast({ title: '请输入密码', icon: 'none' })
return false
}
if (this.registerForm.password.length < 6 || this.registerForm.password.length > 20) {
uni.showToast({ title: '密码长度为6-20位', icon: 'none' })
return false
}
if (this.registerForm.password !== this.registerForm.confirmPassword) {
uni.showToast({ title: '两次密码输入不一致', icon: 'none' })
return false
}
if (!this.registerForm.customer_name) {
uni.showToast({ title: '请输入店铺名称', icon: 'none' })
return false
}
if (!this.registerForm.real_name) {
uni.showToast({ title: '请输入法人名称', icon: 'none' })
return false
}
if (!this.registerForm.company_name) {
uni.showToast({ title: '请输入公司名称', icon: 'none' })
return false
}
if (!this.registerForm.id_card_front) {
uni.showToast({ title: '请上传身份证正面', icon: 'none' })
return false
}
if (!this.registerForm.id_card_back) {
uni.showToast({ title: '请上传身份证反面', icon: 'none' })
return false
}
if (!this.registerForm.business_license) {
uni.showToast({ title: '请上传营业执照', icon: 'none' })
return false
}
if (!this.registerForm.sms_code) {
uni.showToast({ title: '请输入短信验证码', icon: 'none' })
return false
}
if (!this.agreed) {
uni.showToast({ title: '请先同意用户协议', icon: 'none' })
return false
}
return true
},
// 处理注册
async handleRegister() {
if (!this.validateForm()) {
return
}
this.registerLoading = true
try {
// 准备注册数据
const registerData = {
phone: this.registerForm.phone,
password: this.registerForm.password,
customer_name: this.registerForm.customer_name,
real_name: this.registerForm.real_name,
company_name: this.registerForm.company_name,
business_license_image: this.registerForm.business_license,
id_card_front_image: this.registerForm.id_card_front,
id_card_back_image: this.registerForm.id_card_back
}
// 添加验证信息(验证码必填,身份码选填)
registerData.sms_code = this.registerForm.sms_code
if (this.registerForm.referrer_identity_code) {
registerData.referrer_identity_code = this.registerForm.referrer_identity_code
}
const res = await request.post('/back/auth/register', registerData)
if (res.success) {
uni.showToast({
title: '注册成功',
icon: 'success'
})
setTimeout(() => {
uni.navigateBack()
}, 1500)
} else {
uni.showToast({
title: res.message || '注册失败',
icon: 'none'
})
}
} catch (error) {
console.error('注册失败:', error)
uni.showToast({
title: '网络错误,请稍后重试',
icon: 'none'
})
} finally {
this.registerLoading = false
}
},
// 跳转到登录页面
goToLogin() {
uni.navigateBack()
}
}
}
</script>
<style scoped>
.container {
background-color: #f5f5f5;
min-height: 100vh;
}
.register-header {
background: linear-gradient(135deg, #FF4444 0%, #FF6666 100%);
padding: 40rpx 30rpx;
text-align: center;
color: #fff;
}
.page-title {
font-size: 36rpx;
font-weight: bold;
}
.register-form {
padding: 40rpx 30rpx;
}
.section-title {
font-size: 32rpx;
font-weight: bold;
color: #333;
margin: 40rpx 0 30rpx 0;
}
.form-item {
background-color: #fff;
border-radius: 16rpx;
padding: 30rpx;
margin-bottom: 20rpx;
}
.form-label {
display: block;
font-size: 28rpx;
color: #333;
margin-bottom: 20rpx;
}
.form-input {
width: 100%;
font-size: 28rpx;
color: #333;
}
/* 上传区域 */
.upload-section {
margin-bottom: 30rpx;
}
.upload-label {
display: block;
font-size: 28rpx;
color: #333;
margin-bottom: 20rpx;
}
.upload-area {
background-color: #fff;
border-radius: 16rpx;
height: 200rpx;
display: flex;
align-items: center;
justify-content: center;
border: 2rpx dashed #ddd;
}
.upload-image {
width: 100%;
height: 100%;
border-radius: 16rpx;
}
.upload-placeholder {
display: flex;
flex-direction: column;
align-items: center;
color: #999;
}
.upload-placeholder uni-icons {
margin-bottom: 15rpx;
}
.upload-text {
font-size: 24rpx;
}
/* 验证码输入组 */
.verify-section {
margin-bottom: 20rpx;
}
.verify-input-group {
display: flex;
align-items: center;
gap: 20rpx;
}
.verify-input {
flex: 1;
}
.verify-btn {
background-color: #FF4444;
color: #fff;
border: none;
border-radius: 8rpx;
padding: 20rpx 30rpx;
font-size: 24rpx;
white-space: nowrap;
}
.verify-btn:disabled {
background-color: #ccc;
}
/* 用户协议 */
.agreement-section {
margin: 40rpx 0;
}
.agreement-item {
display: flex;
align-items: center;
padding: 20rpx;
}
.agreement-item uni-icons {
margin-right: 15rpx;
}
.agreement-text {
font-size: 24rpx;
color: #666;
}
.agreement-link {
font-size: 24rpx;
color: #FF4444;
text-decoration: underline;
}
/* 注册按钮 */
.register-btn {
background-color: #FF4444;
color: #fff;
border-radius: 50rpx;
height: 100rpx;
font-size: 32rpx;
font-weight: bold;
margin: 40rpx 0;
border: none;
}
.register-btn:disabled {
background-color: #ccc;
}
/* 登录链接 */
.login-link {
text-align: center;
margin-top: 40rpx;
}
.link-text {
font-size: 28rpx;
color: #666;
}
.link-action {
font-size: 28rpx;
color: #FF4444;
text-decoration: underline;
}
</style>
+662
View File
@@ -0,0 +1,662 @@
<template>
<view class="container">
<!-- 状态切换标签 -->
<view class="status-tabs">
<view class="tab-item"
:class="{ active: currentStatus === 'all' }"
@click="switchStatus('all')">
<text class="tab-text">全部</text>
</view>
<view class="tab-item"
:class="{ active: currentStatus === '0' }"
@click="switchStatus('0')">
<text class="tab-text">待付款</text>
</view>
<view class="tab-item"
:class="{ active: currentStatus === '1' }"
@click="switchStatus('1')">
<text class="tab-text">待确认</text>
</view>
<view class="tab-item"
:class="{ active: currentStatus === '2' }"
@click="switchStatus('2')">
<text class="tab-text">已完成</text>
</view>
</view>
<!-- 筛选条件 -->
<view class="filter-bar">
<view class="filter-item" @click="showDatePicker('start')">
<text class="filter-label">开始日期</text>
<text class="filter-value">{{ startDate || '选择日期' }}</text>
</view>
<view class="filter-item" @click="showDatePicker('end')">
<text class="filter-label">结束日期</text>
<text class="filter-value">{{ endDate || '选择日期' }}</text>
</view>
<view class="filter-item" @click="showAmountFilter">
<text class="filter-label">按日期筛选</text>
<text class="filter-value">总金额</text>
</view>
</view>
<!-- 总金额显示 -->
<view class="amount-summary" v-if="totalAmount > 0">
<text class="summary-label">重置</text>
<text class="summary-amount">{{ totalAmount }}</text>
</view>
<!-- 卖单列表 -->
<view class="sales-list">
<view class="sales-item" v-for="(item, index) in salesList" :key="index" @click="goToOrderDetail(item)">
<view class="order-header">
<text class="order-number">订单编号:{{ item.order_no }}</text>
<view class="order-status" :class="getStatusClass(item.order_status)">
<text class="status-text">{{ getStatusText(item.order_status) }}</text>
</view>
</view>
<view class="order-content">
<view class="product-info">
<image :src="getFullImageUrl(getFirstImage(item.product_images))"
class="product-image"
mode="aspectFill">
</image>
<view class="product-details">
<text class="product-name">{{ item.product_name }}</text>
<text class="product-price">¥{{ item.selling_price }}</text>
<text class="product-quantity">×{{ item.quantity }}</text>
</view>
</view>
</view>
<view class="order-footer">
<text class="order-time">下单时间:{{ formatTime(item.created_at) }}</text>
<view class="order-summary">
<!-- <text class="summary-text">共{{ item.quantity }}件商品 运费 ¥0.00 合计:</text> -->
<text class="summary-price">¥{{ item.total_amount }}</text>
</view>
</view>
<view class="order-actions">
<!-- <button class="action-btn detail-btn" @click.stop="goToDetail(item)">
查看详情
</button> -->
<button v-if="item.payment_proof_image"
class="action-btn proof-btn"
@click.stop="viewPaymentProof(item)">
查看凭证
</button>
<button v-if="item.order_status === 1"
class="action-btn confirm-btn"
@click.stop="confirmOrder(item)">
确认发货
</button>
</view>
</view>
</view>
<!-- 空状态 -->
<view class="empty-state" v-if="salesList.length === 0 && !loading">
<uni-icons type="shop" size="100" color="#ccc"></uni-icons>
<text class="empty-text">暂无卖单</text>
</view>
<!-- 加载更多 -->
<view class="load-more" v-if="hasMore && salesList.length > 0">
<text>加载更多...</text>
</view>
</view>
</template>
<script>
import request from '@/utils/request.js'
export default {
data() {
return {
currentStatus: 'all',
startDate: '',
endDate: '',
totalAmount: 0,
salesList: [],
currentPage: 1,
pageSize: 10,
hasMore: true,
loading: false
}
},
onLoad(options) {
// 检查登录状态
const token = uni.getStorageSync('token')
if (!token) {
uni.reLaunch({
url: '/pages/login/login'
})
return
}
if (options.status) {
this.currentStatus = options.status
}
this.loadSales()
},
onReachBottom() {
if (this.hasMore && !this.loading) {
this.loadMore()
}
},
methods: {
// 获取完整的图片URL
getFullImageUrl(url) {
return request.getImageUrl(url)
},
// 获取商品的第一张图片
getFirstImage(images) {
if (!images) return ''
if (typeof images === 'string') {
return images.split(',')[0].trim()
}
if (Array.isArray(images) && images.length > 0) {
return images[0]
}
return ''
},
// 切换状态
switchStatus(status) {
this.currentStatus = status
this.currentPage = 1
this.loadSales()
},
// 显示日期选择器
showDatePicker(type) {
uni.showActionSheet({
itemList: ['今天', '最近7天', '最近30天', '最近90天'],
success: (res) => {
const now = new Date()
let startDate, endDate
switch (res.tapIndex) {
case 0: // 今天
startDate = endDate = this.formatDate(now)
break
case 1: // 最近7天
startDate = this.formatDate(new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000))
endDate = this.formatDate(now)
break
case 2: // 最近30天
startDate = this.formatDate(new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000))
endDate = this.formatDate(now)
break
case 3:
startDate = this.formatDate(new Date(now.getTime() - 90 * 24 * 60 * 60 * 1000))
endDate = this.formatDate(now)
break
}
if (type === 'start') {
this.startDate = startDate
} else {
this.endDate = endDate
}
this.currentPage = 1
this.loadSales()
}
})
},
// 显示金额筛选
showAmountFilter() {
this.startDate = ''
this.endDate = ''
this.currentPage = 1
this.loadSales()
},
// 加载卖单列表
async loadSales() {
this.loading = true
try {
const params = {
page: this.currentPage,
page_size: this.pageSize
}
if (this.currentStatus !== 'all') {
// 状态映射:前端显示状态 -> 后端查询参数
const statusMap = {
'0': 'pending',
'1': 'confirming',
'2': 'completed',
'3': 'cancelled'
}
params.status = statusMap[this.currentStatus] || this.currentStatus
}
if (this.startDate) {
params.start_date = this.startDate
}
if (this.endDate) {
params.end_date = this.endDate
}
const res = await request.get('/back/user/orders/sales', params)
if (res.success) {
const data = res.data
if (this.currentPage === 1) {
this.salesList = data.list || []
} else {
this.salesList = [...this.salesList, ...(data.list || [])]
}
this.hasMore = this.salesList.length < data.total
this.totalAmount = data.total_amount || 0
}
} catch (error) {
console.error('加载卖单失败:', error)
uni.showToast({
title: '加载失败',
icon: 'none'
})
} finally {
this.loading = false
}
},
// 加载更多
loadMore() {
this.currentPage++
this.loadSales()
},
// 获取状态样式类
getStatusClass(status) {
const classMap = {
0: 'status-pending',
1: 'status-confirming',
2: 'status-completed',
3: 'status-cancelled'
}
return classMap[status] || ''
},
// 获取状态文本
getStatusText(status) {
const textMap = {
0: '待付款',
1: '待确认',
2: '已完成',
3: '已取消'
}
return textMap[status] || '未知状态'
},
// 格式化时间
formatTime(time) {
if (!time) return ''
const date = new Date(time)
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`
},
// 格式化日期
formatDate(date) {
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
},
// 跳转到订单详情
goToDetail(order) {
uni.navigateTo({
url: `/pages/order/detail?id=${order.id}&type=sales`
})
},
// 跳转到订单详情页面
goToOrderDetail(order) {
uni.navigateTo({
url: `/pages/orders/detail?id=${order.id}&type=sales`
})
},
// 查看付款凭证
viewPaymentProof(order) {
if (!order.payment_proof_image) {
uni.showToast({
title: '暂无付款凭证',
icon: 'none'
})
return
}
uni.previewImage({
urls: [this.getFullImageUrl(order.payment_proof_image)],
current: 0
})
},
// 确认发货
async confirmOrder(order) {
uni.showModal({
title: '确认发货',
content: `确认向买家发货 ¥${order.total_amount} 的商品吗?确认后买家将收到商品。`,
success: async (res) => {
if (res.confirm) {
try {
const result = await request.put(`/back/user/orders/sales/${order.id}/confirm`)
if (result.success) {
uni.showToast({
title: '确认发货成功',
icon: 'success'
})
this.loadSales()
} else {
throw new Error(result.message || '确认失败')
}
} catch (error) {
console.error('确认发货失败:', error)
uni.showToast({
title: error.message || '确认失败',
icon: 'none'
})
}
}
}
})
},
// 取消订单
async cancelOrder(order) {
uni.showModal({
title: '确认取消',
content: '确定要取消这个订单吗?',
success: async (res) => {
if (res.confirm) {
try {
const result = await request.post(`/back/user/orders/sales/${order.id}/cancel`)
if (result.success) {
uni.showToast({
title: '订单已取消',
icon: 'success'
})
this.loadSales()
}
} catch (error) {
uni.showToast({
title: '取消失败',
icon: 'none'
})
}
}
}
})
}
}
}
</script>
<style scoped>
.container {
background-color: #f5f5f5;
min-height: 100vh;
}
/* 样式与买单页面基本一致,只调整部分颜色和文本 */
.status-tabs {
background-color: #fff;
display: flex;
padding: 0 30rpx;
}
.tab-item {
flex: 1;
text-align: center;
padding: 30rpx 0;
position: relative;
}
.tab-text {
font-size: 28rpx;
color: #666;
}
.tab-item.active .tab-text {
color: #FF4444;
font-weight: bold;
}
.tab-item.active::after {
content: '';
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
width: 60rpx;
height: 4rpx;
background-color: #FF4444;
}
.filter-bar {
background-color: #fff;
display: flex;
padding: 20rpx 30rpx;
border-bottom: 1rpx solid #eee;
}
.filter-item {
flex: 1;
text-align: center;
}
.filter-label {
display: block;
font-size: 24rpx;
color: #999;
margin-bottom: 10rpx;
}
.filter-value {
font-size: 28rpx;
color: #333;
}
.amount-summary {
background-color: #fff;
padding: 20rpx 30rpx;
display: flex;
justify-content: space-between;
align-items: center;
border-bottom: 1rpx solid #eee;
}
.summary-label {
font-size: 28rpx;
color: #007AFF;
}
.summary-amount {
font-size: 32rpx;
font-weight: bold;
color: #FF4444;
}
.sales-list {
padding: 20rpx;
}
.sales-item {
background-color: #fff;
border-radius: 16rpx;
margin-bottom: 20rpx;
overflow: hidden;
}
.order-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 30rpx;
border-bottom: 1rpx solid #f5f5f5;
}
.order-number {
font-size: 24rpx;
color: #666;
}
.order-status {
padding: 8rpx 16rpx;
border-radius: 20rpx;
font-size: 24rpx;
}
.status-pending {
background-color: #FFF2E6;
color: #FF8800;
}
.status-confirming {
background-color: #E6F7FF;
color: #1890FF;
}
.status-completed {
background-color: #F6FFED;
color: #52C41A;
}
.status-cancelled {
background-color: #FFF1F0;
color: #FF4D4F;
}
.order-content {
padding: 30rpx;
}
.product-info {
display: flex;
}
.product-image {
width: 160rpx;
height: 120rpx;
border-radius: 8rpx;
margin-right: 20rpx;
background-color: #f5f5f5;
}
.product-details {
flex: 1;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.product-name {
font-size: 28rpx;
color: #333;
font-weight: bold;
}
.product-price {
font-size: 32rpx;
color: #FF4444;
font-weight: bold;
}
.product-quantity {
font-size: 24rpx;
color: #999;
}
.order-footer {
padding: 30rpx;
border-top: 1rpx solid #f5f5f5;
}
.order-time {
display: block;
font-size: 24rpx;
color: #999;
margin-bottom: 20rpx;
}
.order-summary {
display: flex;
justify-content: space-between;
align-items: center;
}
.summary-text {
font-size: 24rpx;
color: #666;
}
.summary-price {
font-size: 32rpx;
color: #FF4444;
font-weight: bold;
}
.order-actions {
display: flex;
justify-content: flex-end;
padding: 30rpx;
gap: 20rpx;
border-top: 1rpx solid #f5f5f5;
}
.action-btn {
padding: 16rpx 32rpx;
border-radius: 8rpx;
font-size: 24rpx;
border: 1rpx solid #ddd;
}
.detail-btn {
background-color: #fff;
color: #666;
}
.proof-btn {
background-color: #1890FF;
color: #fff;
border-color: #1890FF;
}
.confirm-btn {
background-color: #52C41A;
color: #fff;
border-color: #52C41A;
}
.cancel-btn {
background-color: #fff;
color: #999;
}
.empty-state {
text-align: center;
padding: 200rpx 0;
}
.empty-state uni-icons {
margin-bottom: 40rpx;
}
.empty-text {
font-size: 28rpx;
color: #999;
}
.load-more {
text-align: center;
padding: 40rpx;
color: #999;
font-size: 24rpx;
}
</style>
+366
View File
@@ -0,0 +1,366 @@
<template>
<view class="container">
<!-- 积分概览 -->
<view class="score-header">
<view class="current-score">
<text class="score-label">当前积分</text>
<text class="score-value">{{ scoreStats.current_points || 0 }}</text>
</view>
<view class="score-stats">
<view class="stat-item">
<text class="stat-value">{{ scoreStats.total_income || 0 }}</text>
<text class="stat-label">累计获得</text>
</view>
<view class="stat-item">
<text class="stat-value">{{ scoreStats.total_expense || 0 }}</text>
<text class="stat-label">累计消费</text>
</view>
</view>
</view>
<!-- 筛选栏 -->
<view class="filter-bar">
<view class="filter-item"
:class="{ active: currentFilter === 'all' }"
@click="switchFilter('all')">
<text class="filter-text">全部</text>
</view>
<view class="filter-item"
:class="{ active: currentFilter === 'positive' }"
@click="switchFilter('positive')">
<text class="filter-text">收入</text>
</view>
<view class="filter-item"
:class="{ active: currentFilter === 'negative' }"
@click="switchFilter('negative')">
<text class="filter-text">支出</text>
</view>
</view>
<!-- 积分记录列表 -->
<view class="record-list">
<view class="record-item" v-for="(item, index) in recordList" :key="index">
<view class="record-content">
<view class="record-info">
<text class="record-note">{{ item.note }}</text>
<text class="record-time">{{ formatTime(item.created_at) }}</text>
</view>
<view class="record-amount" :class="{ positive: item.change_number > 0, negative: item.change_number < 0 }">
<text class="amount-text">
{{ item.change_number > 0 ? '+' : '' }}{{ item.change_number }}
</text>
</view>
</view>
</view>
</view>
<!-- 空状态 -->
<view class="empty-state" v-if="recordList.length === 0 && !loading">
<uni-icons type="wallet" size="100" color="#ccc"></uni-icons>
<text class="empty-text">暂无积分记录</text>
</view>
<!-- 加载更多 -->
<view class="load-more" v-if="hasMore && recordList.length > 0">
<text>加载更多...</text>
</view>
<!-- 加载中 -->
<view class="loading" v-if="loading">
<text>加载中...</text>
</view>
</view>
</template>
<script>
import request from '@/utils/request.js'
export default {
data() {
return {
scoreStats: {
current_points: 0,
total_income: 0,
total_expense: 0
},
recordList: [],
currentFilter: 'all',
currentPage: 1,
pageSize: 20,
hasMore: true,
loading: false
}
},
onLoad() {
// 检查登录状态
const token = uni.getStorageSync('token')
if (!token) {
uni.reLaunch({
url: '/pages/login/login'
})
return
}
this.loadScoreStats()
this.loadRecords()
},
onReachBottom() {
if (this.hasMore && !this.loading) {
this.loadMore()
}
},
methods: {
// 加载积分统计信息
async loadScoreStats() {
try {
const res = await request.get('/back/user/scores/stats')
if (res.success) {
this.scoreStats = res.data
}
} catch (error) {
console.error('加载积分统计失败:', error)
}
},
// 加载积分记录
async loadRecords() {
this.loading = true
try {
const params = {
page: this.currentPage,
page_size: this.pageSize
}
if (this.currentFilter !== 'all') {
params.change_type = this.currentFilter
}
const res = await request.get('/back/user/scores/records', params)
if (res.success) {
const data = res.data
if (this.currentPage === 1) {
this.recordList = data.list || []
} else {
this.recordList = [...this.recordList, ...(data.list || [])]
}
this.hasMore = this.recordList.length < data.total
// 更新统计信息
if (data.current_points !== undefined) {
this.scoreStats.current_points = data.current_points
this.scoreStats.total_income = data.total_income || 0
this.scoreStats.total_expense = data.total_expense || 0
}
}
} catch (error) {
console.error('加载积分记录失败:', error)
uni.showToast({
title: '加载失败',
icon: 'none'
})
} finally {
this.loading = false
}
},
// 加载更多
loadMore() {
this.currentPage++
this.loadRecords()
},
// 切换筛选条件
switchFilter(filter) {
this.currentFilter = filter
this.currentPage = 1
this.loadRecords()
},
// 格式化时间
formatTime(time) {
if (!time) return ''
const date = new Date(time)
const now = new Date()
const diffTime = now.getTime() - date.getTime()
const diffDays = Math.floor(diffTime / (24 * 60 * 60 * 1000))
if (diffDays === 0) {
return `今天 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
} else if (diffDays === 1) {
return `昨天 ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
} else if (diffDays < 7) {
return `${diffDays}天前`
} else {
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
}
}
}
}
</script>
<style scoped>
.container {
background-color: #f5f5f5;
min-height: 100vh;
}
/* 积分概览 */
.score-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
padding: 60rpx 40rpx 40rpx;
color: white;
}
.current-score {
text-align: center;
margin-bottom: 40rpx;
}
.score-label {
display: block;
font-size: 28rpx;
opacity: 0.8;
margin-bottom: 10rpx;
}
.score-value {
font-size: 80rpx;
font-weight: bold;
display: block;
}
.score-stats {
display: flex;
justify-content: space-around;
}
.stat-item {
text-align: center;
}
.stat-value {
display: block;
font-size: 36rpx;
font-weight: bold;
margin-bottom: 8rpx;
}
.stat-label {
font-size: 24rpx;
opacity: 0.8;
}
/* 筛选栏 */
.filter-bar {
background-color: #fff;
display: flex;
padding: 0 30rpx;
border-bottom: 1rpx solid #eee;
}
.filter-item {
flex: 1;
text-align: center;
padding: 30rpx 0;
position: relative;
}
.filter-text {
font-size: 28rpx;
color: #666;
}
.filter-item.active .filter-text {
color: #667eea;
font-weight: bold;
}
.filter-item.active::after {
content: '';
position: absolute;
bottom: 0;
left: 50%;
transform: translateX(-50%);
width: 60rpx;
height: 4rpx;
background-color: #667eea;
}
/* 记录列表 */
.record-list {
padding: 20rpx;
}
.record-item {
background-color: #fff;
border-radius: 16rpx;
margin-bottom: 20rpx;
overflow: hidden;
}
.record-content {
display: flex;
align-items: center;
justify-content: space-between;
padding: 30rpx;
}
.record-info {
flex: 1;
}
.record-note {
display: block;
font-size: 30rpx;
color: #333;
font-weight: 500;
margin-bottom: 8rpx;
}
.record-time {
font-size: 24rpx;
color: #999;
}
.record-amount {
text-align: right;
}
.amount-text {
font-size: 32rpx;
font-weight: bold;
}
.record-amount.positive .amount-text {
color: #52C41A;
}
.record-amount.negative .amount-text {
color: #FF4D4F;
}
/* 空状态 */
.empty-state {
text-align: center;
padding: 200rpx 0;
}
.empty-state uni-icons {
margin-bottom: 40rpx;
}
.empty-text {
font-size: 28rpx;
color: #999;
}
/* 加载更多 */
.load-more, .loading {
text-align: center;
padding: 40rpx;
color: #999;
font-size: 24rpx;
}
</style>
+672
View File
@@ -0,0 +1,672 @@
<template>
<view class="container">
<view class="warehouse-list">
<view class="warehouse-item" v-for="(item, index) in warehouseList" :key="item.id">
<view class="product-card">
<image :src="getFullImageUrl(getFirstImage(item.product_images))"
class="product-image"
mode="aspectFill"
@error="onImageError"></image>
<view v-if="!getFirstImage(item.product_images)" class="default-product">
<uni-icons type="image" size="60" color="#666"></uni-icons>
</view>
</view>
<view class="product-info">
<text class="product-name">{{ item.product_name }}</text>
<view class="product-stats">
<text class="stats-text">库存 {{ item.quantity }}件</text>
<text class="stats-text">{{ getProductTypeText(item.product_type) }}</text>
<text class="stats-text" v-if="item.status === 0">已出售</text>
</view>
<view class="product-price">
<text class="purchase-price">购买价:¥{{ (item.purchase_price * item.quantity).toFixed(2) }}</text>
<text class="current-price">当前价值:¥{{ (item.warehouse_price * item.quantity).toFixed(2) }}</text>
</view>
</view>
<view class="product-actions">
<button v-if="item.status === 1"
class="action-btn sell-btn"
@click="sellProduct(item)">
立即挂售
</button>
<button v-else-if="item.status === 0"
class="action-btn disabled-btn"
disabled>
不可出售
</button>
<button v-else
class="action-btn sold-btn"
disabled>
已出售
</button>
</view>
</view>
</view>
<!-- 空状态 -->
<view class="empty-state" v-if="warehouseList.length === 0 && !loading">
<uni-icons type="home" size="100" color="#ccc"></uni-icons>
<text class="empty-text">仓库暂无商品</text>
</view>
<!-- 底部提示 -->
<view class="bottom-tip" v-if="warehouseList.length > 0">
<text class="tip-text">没有更多了</text>
</view>
<!-- 挂售弹窗 -->
<uni-popup ref="sellPopup" type="bottom" border-radius="10px 10px 0 0">
<view class="sell-popup">
<view class="popup-header">
<text class="popup-title">商品挂售</text>
<uni-icons type="close" @click="closeSellPopup" class="close-btn"></uni-icons>
</view>
<view class="popup-content" v-if="selectedItem">
<view class="product-summary">
<image :src="getFullImageUrl(getFirstImage(selectedItem.product_images))"
class="summary-image"
mode="aspectFill"></image>
<view class="summary-info">
<text class="summary-name">{{ selectedItem.product_name }}</text>
<text class="summary-stock">库存:{{ selectedItem.quantity }}件</text>
<text class="summary-price">仓库价值:¥{{ selectedItem.warehouse_price }}/件</text>
</view>
</view>
<view class="sell-form">
<view class="form-item">
<text class="form-label">挂售数量</text>
<view class="quantity-selector">
<button class="quantity-btn" @click="decreaseQuantity" :disabled="sellQuantity <= 1">-</button>
<input type="number" v-model.number="sellQuantity" class="quantity-input" :max="selectedItem.quantity" min="1">
<button class="quantity-btn" @click="increaseQuantity" :disabled="sellQuantity >= selectedItem.quantity">+</button>
</view>
</view>
<view class="form-item">
<text class="form-label">出售价格</text>
<view class="price-input-wrap">
<text class="price-symbol">¥</text>
<input disabled type="digit" v-model="sellPrice" class="price-input" placeholder="请输入出售价格">
</view>
</view>
<view class="form-item">
<text class="form-label">商品描述</text>
<textarea v-model="sellDescription" class="description-input" placeholder="请描述商品的具体情况..." maxlength="500"></textarea>
</view>
<!-- <view class="form-item">
<text class="form-label">商品成色</text>
<view class="condition-selector">
<view class="condition-item"
v-for="condition in conditionOptions"
:key="condition.value"
:class="{ active: sellCondition === condition.value }"
@click="sellCondition = condition.value">
<text>{{ condition.label }}</text>
</view>
</view>
</view> -->
</view>
<view class="sell-summary">
<text class="summary-text">挂售 {{ sellQuantity }} 件,总价值 ¥{{ (sellPrice * sellQuantity).toFixed(2) }}</text>
</view>
</view>
<view class="popup-footer">
<button class="cancel-btn" @click="closeSellPopup">取消</button>
<button class="confirm-btn" @click="confirmSell" :disabled="!canSubmit">确认挂售</button>
</view>
</view>
</uni-popup>
</view>
</template>
<script>
import request from '@/utils/request.js'
export default {
data() {
return {
warehouseList: [],
loading: false,
// 挂售相关数据
selectedItem: null,
sellQuantity: 1,
sellPrice: '',
sellDescription: '',
sellCondition: '九成新',
conditionOptions: [
{ label: '全新', value: '全新' },
{ label: '九成新', value: '九成新' },
{ label: '八成新', value: '八成新' },
{ label: '七成新', value: '七成新' },
{ label: '六成新', value: '六成新' },
{ label: '其他', value: '其他' }
],
submitting: false
}
},
computed: {
canSubmit() {
return this.sellQuantity > 0 &&
this.sellQuantity <= (this.selectedItem?.quantity || 0) &&
this.sellPrice > 0 &&
this.sellDescription.trim() &&
!this.submitting
}
},
onLoad() {
// 检查登录状态
const token = uni.getStorageSync('token')
if (!token) {
uni.reLaunch({
url: '/pages/login/login'
})
return
}
this.loadWarehouse()
},
onShow() {
this.loadWarehouse()
},
methods: {
// 获取完整的图片URL
getFullImageUrl(url) {
return request.getImageUrl(url)
},
// 获取商品的第一张图片
getFirstImage(images) {
if (!images) return ''
if (typeof images === 'string') {
return images.split(',')[0].trim()
}
if (Array.isArray(images) && images.length > 0) {
return images[0]
}
return ''
},
// 获取商品类型文本
getProductTypeText(type) {
return type === 1 ? '一级商品' : '二级商品'
},
// 图片加载错误处理
onImageError() {
console.log('图片加载失败')
},
// 加载仓库数据
async loadWarehouse() {
this.loading = true
try {
const res = await request.get('/back/user/warehouse', {
page: 1,
page_size: 50
})
if (res.success) {
this.warehouseList = res.data.list || []
}
} catch (error) {
console.error('加载仓库失败:', error)
uni.showToast({
title: '加载失败',
icon: 'none'
})
} finally {
this.loading = false
}
},
// 挂售商品
sellProduct(item) {
if (item.quantity <= 0) {
uni.showToast({
title: '库存不足,无法挂售',
icon: 'none'
})
return
}
// 设置选中商品并重置表单
this.selectedItem = item
this.sellQuantity = 1
this.sellPrice = item.warehouse_price.toString()
this.sellDescription = `${item.product_name} - 来自个人仓库`
this.sellCondition = '九成新'
this.submitting = false
// 打开挂售弹窗
this.$refs.sellPopup.open()
},
// 关闭挂售弹窗
closeSellPopup() {
this.$refs.sellPopup.close()
this.selectedItem = null
},
// 减少数量
decreaseQuantity() {
if (this.sellQuantity > 1) {
this.sellQuantity--
}
},
// 增加数量
increaseQuantity() {
if (this.sellQuantity < this.selectedItem.quantity) {
this.sellQuantity++
}
},
// 确认挂售
async confirmSell() {
if (!this.canSubmit) return
this.submitting = true
try {
const sellData = {
quantity: this.sellQuantity,
price: parseFloat(this.sellPrice),
description: this.sellDescription.trim(),
condition: this.sellCondition
}
const res = await request.post(`/back/user/warehouse/${this.selectedItem.id}/sell`, sellData)
if (res.success) {
uni.showToast({
title: '挂售成功',
icon: 'success'
})
this.closeSellPopup()
this.loadWarehouse() // 重新加载仓库数据
} else {
throw new Error(res.message || '挂售失败')
}
} catch (error) {
console.error('挂售失败:', error)
uni.showToast({
title: error.message || '挂售失败',
icon: 'none'
})
} finally {
this.submitting = false
}
}
}
}
</script>
<style scoped>
.container {
background-color: #f5f5f5;
min-height: 100vh;
padding: 20rpx;
}
.warehouse-list {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 20rpx;
}
.warehouse-item {
background-color: #fff;
border-radius: 16rpx;
padding: 20rpx;
box-shadow: 0 2rpx 8rpx rgba(0,0,0,0.1);
}
.product-card {
width: 100%;
height: 200rpx;
border-radius: 12rpx;
overflow: hidden;
margin-bottom: 20rpx;
background-color: #333;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
position: relative;
}
.product-image {
width: 100%;
height: 100%;
}
.default-product {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
background-color: #f5f5f5;
}
.product-info {
margin-bottom: 20rpx;
}
.product-name {
display: block;
font-size: 28rpx;
font-weight: bold;
color: #333;
margin-bottom: 15rpx;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.product-stats {
margin-bottom: 15rpx;
}
.stats-text {
display: block;
font-size: 24rpx;
color: #999;
margin-bottom: 8rpx;
}
.product-price {
margin-bottom: 10rpx;
}
.current-price {
font-size: 32rpx;
font-weight: bold;
color: #FF4444;
}
.product-actions {
text-align: center;
}
.action-btn {
width: 100%;
padding: 20rpx;
border-radius: 8rpx;
font-size: 24rpx;
border: none;
}
.sell-btn {
background-color: #FF4444;
color: #fff;
}
.disabled-btn {
background-color: #f5f5f5;
color: #999;
}
.sold-btn {
background-color: #f0f0f0;
color: #ccc;
}
.purchase-price {
font-size: 24rpx;
color: #999;
margin-bottom: 8rpx;
}
/* 空状态 */
.empty-state {
text-align: center;
padding: 200rpx 0;
grid-column: 1 / -1;
}
.empty-state uni-icons {
margin-bottom: 40rpx;
}
.empty-text {
font-size: 28rpx;
color: #999;
}
/* 底部提示 */
.bottom-tip {
text-align: center;
padding: 40rpx;
color: #999;
font-size: 24rpx;
grid-column: 1 / -1;
}
/* 挂售弹窗样式 */
.sell-popup {
background-color: #fff;
border-radius: 20rpx 20rpx 0 0;
padding: 0;
max-height: 80vh;
display: flex;
flex-direction: column;
}
.popup-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 30rpx;
border-bottom: 1rpx solid #f5f5f5;
}
.popup-title {
font-size: 32rpx;
font-weight: bold;
color: #333;
}
.close-btn {
padding: 10rpx;
color: #999;
}
.popup-content {
flex: 1;
padding: 30rpx;
overflow-y: auto;
}
.product-summary {
display: flex;
margin-bottom: 40rpx;
padding: 20rpx;
background-color: #f8f9fa;
border-radius: 12rpx;
}
.summary-image {
width: 120rpx;
height: 120rpx;
border-radius: 8rpx;
margin-right: 20rpx;
}
.summary-info {
flex: 1;
display: flex;
flex-direction: column;
justify-content: space-between;
}
.summary-name {
font-size: 28rpx;
font-weight: bold;
color: #333;
margin-bottom: 8rpx;
}
.summary-stock,
.summary-price {
font-size: 24rpx;
color: #666;
margin-bottom: 4rpx;
}
.sell-form {
margin-bottom: 30rpx;
}
.form-item {
margin-bottom: 30rpx;
}
.form-label {
display: block;
font-size: 28rpx;
color: #333;
margin-bottom: 15rpx;
font-weight: 500;
}
.quantity-selector {
display: flex;
align-items: center;
justify-content: center;
}
.quantity-btn {
width: 60rpx;
height: 60rpx;
border: 1rpx solid #ddd;
background-color: #fff;
color: #333;
font-size: 32rpx;
border-radius: 8rpx;
display: flex;
align-items: center;
justify-content: center;
}
.quantity-btn:disabled {
background-color: #f5f5f5;
color: #ccc;
}
.quantity-input {
width: 120rpx;
height: 60rpx;
text-align: center;
border: 1rpx solid #ddd;
border-left: none;
border-right: none;
font-size: 28rpx;
background-color: #fff;
}
.price-input-wrap {
display: flex;
align-items: center;
border: 1rpx solid #ddd;
border-radius: 8rpx;
padding: 0 20rpx;
background-color: #fff;
}
.price-symbol {
font-size: 28rpx;
color: #666;
margin-right: 10rpx;
}
.price-input {
flex: 1;
height: 80rpx;
font-size: 28rpx;
border: none;
background: none;
}
.description-input {
width: 100%;
min-height: 120rpx;
padding: 20rpx;
border: 1rpx solid #ddd;
border-radius: 8rpx;
font-size: 28rpx;
line-height: 1.5;
background-color: #fff;
}
.condition-selector {
display: flex;
flex-wrap: wrap;
gap: 15rpx;
}
.condition-item {
padding: 15rpx 25rpx;
border: 1rpx solid #ddd;
border-radius: 30rpx;
font-size: 24rpx;
color: #666;
background-color: #fff;
}
.condition-item.active {
border-color: #FF4444;
background-color: #FF4444;
color: #fff;
}
.sell-summary {
padding: 20rpx;
background-color: #f8f9fa;
border-radius: 8rpx;
text-align: center;
}
.summary-text {
font-size: 28rpx;
color: #333;
font-weight: 500;
}
.popup-footer {
display: flex;
padding: 30rpx;
border-top: 1rpx solid #f5f5f5;
gap: 20rpx;
}
.cancel-btn,
.confirm-btn {
flex: 1;
height: 80rpx;
border-radius: 8rpx;
font-size: 28rpx;
border: none;
}
.cancel-btn {
background-color: #f5f5f5;
color: #666;
}
.confirm-btn {
background-color: #FF4444;
color: #fff;
}
.confirm-btn:disabled {
background-color: #ccc;
color: #999;
}
</style>
Binary file not shown.

After

Width:  |  Height:  |  Size: 75 KiB

+20
View File
@@ -0,0 +1,20 @@
@font-face {
font-family: "customicons"; /* Project id 2878519 */
src:url('/static/customicons.ttf') format('truetype');
}
.customicons {
font-family: "customicons" !important;
}
.youxi:before {
content: "\e60e";
}
.wenjian:before {
content: "\e60f";
}
.zhuanfa:before {
content: "\e610";
}
Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.9 KiB

+1
View File
@@ -0,0 +1 @@
@import '@/uni_modules/uni-scss/variables.scss';
+33
View File
@@ -0,0 +1,33 @@
## 1.2.2(2023-01-28)
- 修复 运行/打包 控制台警告问题
## 1.2.1(2022-09-05)
- 修复 当 text 超过 max-num 时,badge 的宽度计算是根据 text 的长度计算,更改为 css 计算实际展示宽度,详见:[https://ask.dcloud.net.cn/question/150473](https://ask.dcloud.net.cn/question/150473)
## 1.2.0(2021-11-19)
- 优化 组件UI,并提供设计资源,详见:[https://uniapp.dcloud.io/component/uniui/resource](https://uniapp.dcloud.io/component/uniui/resource)
- 文档迁移,详见:[https://uniapp.dcloud.io/component/uniui/uni-badge](https://uniapp.dcloud.io/component/uniui/uni-badge)
## 1.1.7(2021-11-08)
- 优化 升级ui
- 修改 size 属性默认值调整为 small
- 修改 type 属性,默认值调整为 error,info 替换 default
## 1.1.6(2021-09-22)
- 修复 在字节小程序上样式不生效的 bug
## 1.1.5(2021-07-30)
- 组件兼容 vue3,如何创建vue3项目,详见 [uni-app 项目支持 vue3 介绍](https://ask.dcloud.net.cn/article/37834)
## 1.1.4(2021-07-29)
- 修复 去掉 nvue 不支持css 的 align-self 属性,nvue 下不暂支持 absolute 属性
## 1.1.3(2021-06-24)
- 优化 示例项目
## 1.1.1(2021-05-12)
- 新增 组件示例地址
## 1.1.0(2021-05-12)
- 新增 uni-badge 的 absolute 属性,支持定位
- 新增 uni-badge 的 offset 属性,支持定位偏移
- 新增 uni-badge 的 is-dot 属性,支持仅显示有一个小点
- 新增 uni-badge 的 max-num 属性,支持自定义封顶的数字值,超过 99 显示99+
- 优化 uni-badge 属性 custom-style, 支持以对象形式自定义样式
## 1.0.7(2021-05-07)
- 修复 uni-badge 在 App 端,数字小于10时不是圆形的bug
- 修复 uni-badge 在父元素不是 flex 布局时,宽度缩小的bug
- 新增 uni-badge 属性 custom-style, 支持自定义样式
## 1.0.6(2021-02-04)
- 调整为uni_modules目录规范
@@ -0,0 +1,268 @@
<template>
<view class="uni-badge--x">
<slot />
<text v-if="text" :class="classNames" :style="[positionStyle, customStyle, dotStyle]"
class="uni-badge" @click="onClick()">{{displayValue}}</text>
</view>
</template>
<script>
/**
* Badge 数字角标
* @description 数字角标一般和其它控件(列表、9宫格等)配合使用,用于进行数量提示,默认为实心灰色背景
* @tutorial https://ext.dcloud.net.cn/plugin?id=21
* @property {String} text 角标内容
* @property {String} size = [normal|small] 角标内容
* @property {String} type = [info|primary|success|warning|error] 颜色类型
* @value info 灰色
* @value primary 蓝色
* @value success 绿色
* @value warning 黄色
* @value error 红色
* @property {String} inverted = [true|false] 是否无需背景颜色
* @property {Number} maxNum 展示封顶的数字值,超过 99 显示 99+
* @property {String} absolute = [rightTop|rightBottom|leftBottom|leftTop] 开启绝对定位, 角标将定位到其包裹的标签的四角上
* @value rightTop 右上
* @value rightBottom 右下
* @value leftTop 左上
* @value leftBottom 左下
* @property {Array[number]} offset 距定位角中心点的偏移量,只有存在 absolute 属性时有效,例如:[-10, -10] 表示向外偏移 10px,[10, 10] 表示向 absolute 指定的内偏移 10px
* @property {String} isDot = [true|false] 是否显示为一个小点
* @event {Function} click 点击 Badge 触发事件
* @example <uni-badge text="1"></uni-badge>
*/
export default {
name: 'UniBadge',
emits: ['click'],
props: {
type: {
type: String,
default: 'error'
},
inverted: {
type: Boolean,
default: false
},
isDot: {
type: Boolean,
default: false
},
maxNum: {
type: Number,
default: 99
},
absolute: {
type: String,
default: ''
},
offset: {
type: Array,
default () {
return [0, 0]
}
},
text: {
type: [String, Number],
default: ''
},
size: {
type: String,
default: 'small'
},
customStyle: {
type: Object,
default () {
return {}
}
}
},
data() {
return {};
},
computed: {
width() {
return String(this.text).length * 8 + 12
},
classNames() {
const {
inverted,
type,
size,
absolute
} = this
return [
inverted ? 'uni-badge--' + type + '-inverted' : '',
'uni-badge--' + type,
'uni-badge--' + size,
absolute ? 'uni-badge--absolute' : ''
].join(' ')
},
positionStyle() {
if (!this.absolute) return {}
let w = this.width / 2,
h = 10
if (this.isDot) {
w = 5
h = 5
}
const x = `${- w + this.offset[0]}px`
const y = `${- h + this.offset[1]}px`
const whiteList = {
rightTop: {
right: x,
top: y
},
rightBottom: {
right: x,
bottom: y
},
leftBottom: {
left: x,
bottom: y
},
leftTop: {
left: x,
top: y
}
}
const match = whiteList[this.absolute]
return match ? match : whiteList['rightTop']
},
dotStyle() {
if (!this.isDot) return {}
return {
width: '10px',
minWidth: '0',
height: '10px',
padding: '0',
borderRadius: '10px'
}
},
displayValue() {
const {
isDot,
text,
maxNum
} = this
return isDot ? '' : (Number(text) > maxNum ? `${maxNum}+` : text)
}
},
methods: {
onClick() {
this.$emit('click');
}
}
};
</script>
<style lang="scss" >
$uni-primary: #2979ff !default;
$uni-success: #4cd964 !default;
$uni-warning: #f0ad4e !default;
$uni-error: #dd524d !default;
$uni-info: #909399 !default;
$bage-size: 12px;
$bage-small: scale(0.8);
.uni-badge--x {
/* #ifdef APP-NVUE */
// align-self: flex-start;
/* #endif */
/* #ifndef APP-NVUE */
display: inline-block;
/* #endif */
position: relative;
}
.uni-badge--absolute {
position: absolute;
}
.uni-badge--small {
transform: $bage-small;
transform-origin: center center;
}
.uni-badge {
/* #ifndef APP-NVUE */
display: flex;
overflow: hidden;
box-sizing: border-box;
font-feature-settings: "tnum";
min-width: 20px;
/* #endif */
justify-content: center;
flex-direction: row;
height: 20px;
padding: 0 4px;
line-height: 18px;
color: #fff;
border-radius: 100px;
background-color: $uni-info;
background-color: transparent;
border: 1px solid #fff;
text-align: center;
font-family: 'Helvetica Neue', Helvetica, sans-serif;
font-size: $bage-size;
/* #ifdef H5 */
z-index: 999;
cursor: pointer;
/* #endif */
&--info {
color: #fff;
background-color: $uni-info;
}
&--primary {
background-color: $uni-primary;
}
&--success {
background-color: $uni-success;
}
&--warning {
background-color: $uni-warning;
}
&--error {
background-color: $uni-error;
}
&--inverted {
padding: 0 5px 0 0;
color: $uni-info;
}
&--info-inverted {
color: $uni-info;
background-color: transparent;
}
&--primary-inverted {
color: $uni-primary;
background-color: transparent;
}
&--success-inverted {
color: $uni-success;
background-color: transparent;
}
&--warning-inverted {
color: $uni-warning;
background-color: transparent;
}
&--error-inverted {
color: $uni-error;
background-color: transparent;
}
}
</style>
+85
View File
@@ -0,0 +1,85 @@
{
"id": "uni-badge",
"displayName": "uni-badge 数字角标",
"version": "1.2.2",
"description": "数字角标(徽章)组件,在元素周围展示消息提醒,一般用于列表、九宫格、按钮等地方。",
"keywords": [
"",
"badge",
"uni-ui",
"uniui",
"数字角标",
"徽章"
],
"repository": "https://github.com/dcloudio/uni-ui",
"engines": {
"HBuilderX": ""
},
"directories": {
"example": "../../temps/example_temps"
},
"dcloudext": {
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "https://www.npmjs.com/package/@dcloudio/uni-ui",
"type": "component-vue"
},
"uni_modules": {
"dependencies": ["uni-scss"],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y"
},
"client": {
"App": {
"app-vue": "y",
"app-nvue": "y"
},
"H5-mobile": {
"Safari": "y",
"Android Browser": "y",
"微信浏览器(Android)": "y",
"QQ浏览器(Android)": "y"
},
"H5-pc": {
"Chrome": "y",
"IE": "y",
"Edge": "y",
"Firefox": "y",
"Safari": "y"
},
"小程序": {
"微信": "y",
"阿里": "y",
"百度": "y",
"字节跳动": "y",
"QQ": "y"
},
"快应用": {
"华为": "y",
"联盟": "y"
},
"Vue": {
"vue2": "y",
"vue3": "y"
}
}
}
}
}
+10
View File
@@ -0,0 +1,10 @@
## Badge 数字角标
> **组件名:uni-badge**
> 代码块: `uBadge`
数字角标一般和其它控件(列表、9宫格等)配合使用,用于进行数量提示,默认为实心灰色背景,
### [查看文档](https://uniapp.dcloud.io/component/uniui/uni-badge)
#### 如使用过程中有任何问题,或者您对uni-ui有一些好的建议,欢迎加入 uni-ui 交流群:871950839
@@ -0,0 +1,6 @@
## 0.1.2(2022-06-08)
- 修复 微信小程序 separator 不显示的Bug
## 0.1.1(2022-06-02)
- 新增 支持 uni.scss 修改颜色
## 0.1.0(2022-04-21)
- 初始化
@@ -0,0 +1,126 @@
<template>
<view class="uni-breadcrumb-item">
<view :class="{
'uni-breadcrumb-item--slot': true,
'uni-breadcrumb-item--slot-link': to && currentPage !== to
}" @click="navTo">
<slot />
</view>
<i v-if="separatorClass" class="uni-breadcrumb-item--separator" :class="separatorClass" />
<text v-else class="uni-breadcrumb-item--separator">{{ separator }}</text>
</view>
</template>
<script>
/**
* BreadcrumbItem 面包屑导航子组件
* @property {String/Object} to 路由跳转页面路径/对象
* @property {Boolean} replace 在使用 to 进行路由跳转时,启用 replace 将不会向 history 添加新记录(仅 h5 支持)
*/
export default {
data() {
return {
currentPage: ""
}
},
options: {
// #ifdef MP-TOUTIAO
virtualHost: false,
// #endif
// #ifndef MP-TOUTIAO
virtualHost: true
// #endif
},
props: {
to: {
type: String,
default: ''
},
replace:{
type: Boolean,
default: false
}
},
inject: {
uniBreadcrumb: {
from: "uniBreadcrumb",
default: null
}
},
created(){
const pages = getCurrentPages()
const page = pages[pages.length-1]
if(page){
this.currentPage = `/${page.route}`
}
},
computed: {
separator() {
return this.uniBreadcrumb.separator
},
separatorClass() {
return this.uniBreadcrumb.separatorClass
}
},
methods: {
navTo() {
const { to } = this
if (!to || this.currentPage === to){
return
}
if(this.replace){
uni.redirectTo({
url:to
})
}else{
uni.navigateTo({
url:to
})
}
}
}
}
</script>
<style lang="scss">
$uni-primary: #2979ff !default;
$uni-base-color: #6a6a6a !default;
$uni-main-color: #3a3a3a !default;
.uni-breadcrumb-item {
display: flex;
align-items: center;
white-space: nowrap;
font-size: 14px;
&--slot {
color: $uni-base-color;
padding: 0 10px;
&-link {
color: $uni-main-color;
font-weight: bold;
/* #ifndef APP-NVUE */
cursor: pointer;
/* #endif */
&:hover {
color: $uni-primary;
}
}
}
&--separator {
font-size: 12px;
color: $uni-base-color;
}
&:first-child &--slot {
padding-left: 0;
}
&:last-child &--separator {
display: none;
}
}
</style>
@@ -0,0 +1,46 @@
<template>
<view class="uni-breadcrumb">
<slot />
</view>
</template>
<script>
/**
* Breadcrumb 面包屑导航父组件
* @description 显示当前页面的路径,快速返回之前的任意页面
* @tutorial https://ext.dcloud.net.cn/plugin?id=xxx
* @property {String} separator 分隔符,默认为斜杠'/'
* @property {String} separatorClass 图标分隔符 class
*/
export default {
options: {
// #ifdef MP-TOUTIAO
virtualHost: false,
// #endif
// #ifndef MP-TOUTIAO
virtualHost: true
// #endif
},
props: {
separator: {
type: String,
default: '/'
},
separatorClass: {
type: String,
default: ''
}
},
provide() {
return {
uniBreadcrumb: this
}
}
}
</script>
<style lang="scss">
.uni-breadcrumb {
display: flex;
}
</style>
@@ -0,0 +1,88 @@
{
"id": "uni-breadcrumb",
"displayName": "uni-breadcrumb 面包屑",
"version": "0.1.2",
"description": "Breadcrumb 面包屑",
"keywords": [
"uni-breadcrumb",
"breadcrumb",
"uni-ui",
"面包屑导航",
"面包屑"
],
"repository": "",
"engines": {
"HBuilderX": "^3.1.0"
},
"directories": {
"example": "../../temps/example_temps"
},
"dcloudext": {
"category": [
"前端组件",
"通用组件"
],
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": ""
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y"
},
"client": {
"Vue": {
"vue2": "y",
"vue3": "y"
},
"App": {
"app-vue": "y",
"app-nvue": "n"
},
"H5-mobile": {
"Safari": "y",
"Android Browser": "y",
"微信浏览器(Android)": "y",
"QQ浏览器(Android)": "y"
},
"H5-pc": {
"Chrome": "y",
"IE": "y",
"Edge": "y",
"Firefox": "y",
"Safari": "y"
},
"小程序": {
"微信": "y",
"阿里": "u",
"百度": "u",
"字节跳动": "u",
"QQ": "u",
"京东": "u"
},
"快应用": {
"华为": "u",
"联盟": "u"
}
}
}
}
}
@@ -0,0 +1,66 @@
## breadcrumb 面包屑导航
> **组件名:uni-breadcrumb**
> 代码块: `ubreadcrumb`
显示当前页面的路径,快速返回之前的任意页面。
### 安装方式
本组件符合[easycom](https://uniapp.dcloud.io/collocation/pages?id=easycom)规范,`HBuilderX 2.5.5`起,只需将本组件导入项目,在页面`template`中即可直接使用,无需在页面中`import`和注册`components`。
如需通过`npm`方式使用`uni-ui`组件,另见文档:[https://ext.dcloud.net.cn/plugin?id=55](https://ext.dcloud.net.cn/plugin?id=55)
### 基本用法
在 ``template`` 中使用组件
```html
<uni-breadcrumb separator="/">
<uni-breadcrumb-item v-for="(route,index) in routes" :key="index" :to="route.to">{{route.name}}</uni-breadcrumb-item>
</uni-breadcrumb>
```
```js
export default {
name: "uni-stat-breadcrumb",
data() {
return {
routes: [{
to: '/A',
name: 'A页面'
}, {
to: '/B',
name: 'B页面'
}, {
to: '/C',
name: 'C页面'
}]
};
}
}
```
## API
### Breadcrumb Props
|属性名 |类型 |默认值 |说明 |
|:-: |:-: |:-: |:-: |
|separator |String |斜杠'/' |分隔符 |
|separatorClass |String | |图标分隔符 class |
### Breadcrumb Item Props
|属性名 |类型 |默认值 |说明 |
|:-: |:-: |:-: |:-: |
|to |String | |路由跳转页面路径 |
|replace|Boolean | |在使用 to 进行路由跳转时,启用 replace 将不会向 history 添加新记录(仅 h5 支持) |
## 组件示例
点击查看:[https://hellouniapp.dcloud.net.cn/pages/extUI/breadcrumb/breadcrumb](https://hellouniapp.dcloud.net.cn/pages/extUI/breadcrumb/breadcrumb)
@@ -0,0 +1,28 @@
## 1.4.11(2024-01-10)
- 修复 回到今天时,月份显示不一致问题
## 1.4.10(2023-04-10)
- 修复 某些情况 monthSwitch 未触发的Bug
## 1.4.9(2023-02-02)
- 修复 某些情况切换月份错误的Bug
## 1.4.8(2023-01-30)
- 修复 某些情况切换月份错误的Bug [详情](https://ask.dcloud.net.cn/question/161964)
## 1.4.7(2022-09-16)
- 优化 支持使用 uni-scss 控制主题色
## 1.4.6(2022-09-08)
- 修复 表头年月切换,导致改变当前日期为选择月1号,且未触发change事件的Bug
## 1.4.5(2022-02-25)
- 修复 条件编译 nvue 不支持的 css 样式的Bug
## 1.4.4(2022-02-25)
- 修复 条件编译 nvue 不支持的 css 样式的Bug
## 1.4.3(2021-09-22)
- 修复 startDate、 endDate 属性失效的Bug
## 1.4.2(2021-08-24)
- 新增 支持国际化
## 1.4.1(2021-08-05)
- 修复 弹出层被 tabbar 遮盖的Bug
## 1.4.0(2021-07-30)
- 组件兼容 vue3,如何创建vue3项目,详见 [uni-app 项目支持 vue3 介绍](https://ask.dcloud.net.cn/article/37834)
## 1.3.16(2021-05-12)
- 新增 组件示例地址
## 1.3.15(2021-02-04)
- 调整为uni_modules目录规范
@@ -0,0 +1,546 @@
/**
* @1900-2100区间内的公历、农历互转
* @charset UTF-8
* @github https://github.com/jjonline/calendar.js
* @Author Jea杨(JJonline@JJonline.Cn)
* @Time 2014-7-21
* @Time 2016-8-13 Fixed 2033hex、Attribution Annals
* @Time 2016-9-25 Fixed lunar LeapMonth Param Bug
* @Time 2017-7-24 Fixed use getTerm Func Param Error.use solar year,NOT lunar year
* @Version 1.0.3
* @公历转农历:calendar.solar2lunar(1987,11,01); //[you can ignore params of prefix 0]
* @农历转公历:calendar.lunar2solar(1987,09,10); //[you can ignore params of prefix 0]
*/
/* eslint-disable */
var calendar = {
/**
* 农历1900-2100的润大小信息表
* @Array Of Property
* @return Hex
*/
lunarInfo: [0x04bd8, 0x04ae0, 0x0a570, 0x054d5, 0x0d260, 0x0d950, 0x16554, 0x056a0, 0x09ad0, 0x055d2, // 1900-1909
0x04ae0, 0x0a5b6, 0x0a4d0, 0x0d250, 0x1d255, 0x0b540, 0x0d6a0, 0x0ada2, 0x095b0, 0x14977, // 1910-1919
0x04970, 0x0a4b0, 0x0b4b5, 0x06a50, 0x06d40, 0x1ab54, 0x02b60, 0x09570, 0x052f2, 0x04970, // 1920-1929
0x06566, 0x0d4a0, 0x0ea50, 0x06e95, 0x05ad0, 0x02b60, 0x186e3, 0x092e0, 0x1c8d7, 0x0c950, // 1930-1939
0x0d4a0, 0x1d8a6, 0x0b550, 0x056a0, 0x1a5b4, 0x025d0, 0x092d0, 0x0d2b2, 0x0a950, 0x0b557, // 1940-1949
0x06ca0, 0x0b550, 0x15355, 0x04da0, 0x0a5b0, 0x14573, 0x052b0, 0x0a9a8, 0x0e950, 0x06aa0, // 1950-1959
0x0aea6, 0x0ab50, 0x04b60, 0x0aae4, 0x0a570, 0x05260, 0x0f263, 0x0d950, 0x05b57, 0x056a0, // 1960-1969
0x096d0, 0x04dd5, 0x04ad0, 0x0a4d0, 0x0d4d4, 0x0d250, 0x0d558, 0x0b540, 0x0b6a0, 0x195a6, // 1970-1979
0x095b0, 0x049b0, 0x0a974, 0x0a4b0, 0x0b27a, 0x06a50, 0x06d40, 0x0af46, 0x0ab60, 0x09570, // 1980-1989
0x04af5, 0x04970, 0x064b0, 0x074a3, 0x0ea50, 0x06b58, 0x05ac0, 0x0ab60, 0x096d5, 0x092e0, // 1990-1999
0x0c960, 0x0d954, 0x0d4a0, 0x0da50, 0x07552, 0x056a0, 0x0abb7, 0x025d0, 0x092d0, 0x0cab5, // 2000-2009
0x0a950, 0x0b4a0, 0x0baa4, 0x0ad50, 0x055d9, 0x04ba0, 0x0a5b0, 0x15176, 0x052b0, 0x0a930, // 2010-2019
0x07954, 0x06aa0, 0x0ad50, 0x05b52, 0x04b60, 0x0a6e6, 0x0a4e0, 0x0d260, 0x0ea65, 0x0d530, // 2020-2029
0x05aa0, 0x076a3, 0x096d0, 0x04afb, 0x04ad0, 0x0a4d0, 0x1d0b6, 0x0d250, 0x0d520, 0x0dd45, // 2030-2039
0x0b5a0, 0x056d0, 0x055b2, 0x049b0, 0x0a577, 0x0a4b0, 0x0aa50, 0x1b255, 0x06d20, 0x0ada0, // 2040-2049
/** Add By JJonline@JJonline.Cn**/
0x14b63, 0x09370, 0x049f8, 0x04970, 0x064b0, 0x168a6, 0x0ea50, 0x06b20, 0x1a6c4, 0x0aae0, // 2050-2059
0x0a2e0, 0x0d2e3, 0x0c960, 0x0d557, 0x0d4a0, 0x0da50, 0x05d55, 0x056a0, 0x0a6d0, 0x055d4, // 2060-2069
0x052d0, 0x0a9b8, 0x0a950, 0x0b4a0, 0x0b6a6, 0x0ad50, 0x055a0, 0x0aba4, 0x0a5b0, 0x052b0, // 2070-2079
0x0b273, 0x06930, 0x07337, 0x06aa0, 0x0ad50, 0x14b55, 0x04b60, 0x0a570, 0x054e4, 0x0d160, // 2080-2089
0x0e968, 0x0d520, 0x0daa0, 0x16aa6, 0x056d0, 0x04ae0, 0x0a9d4, 0x0a2d0, 0x0d150, 0x0f252, // 2090-2099
0x0d520], // 2100
/**
* 公历每个月份的天数普通表
* @Array Of Property
* @return Number
*/
solarMonth: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
/**
* 天干地支之天干速查表
* @Array Of Property trans["甲","乙","丙","丁","戊","己","庚","辛","壬","癸"]
* @return Cn string
*/
Gan: ['\u7532', '\u4e59', '\u4e19', '\u4e01', '\u620a', '\u5df1', '\u5e9a', '\u8f9b', '\u58ec', '\u7678'],
/**
* 天干地支之地支速查表
* @Array Of Property
* @trans["子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"]
* @return Cn string
*/
Zhi: ['\u5b50', '\u4e11', '\u5bc5', '\u536f', '\u8fb0', '\u5df3', '\u5348', '\u672a', '\u7533', '\u9149', '\u620c', '\u4ea5'],
/**
* 天干地支之地支速查表<=>生肖
* @Array Of Property
* @trans["鼠","牛","虎","兔","龙","蛇","马","羊","猴","鸡","狗","猪"]
* @return Cn string
*/
Animals: ['\u9f20', '\u725b', '\u864e', '\u5154', '\u9f99', '\u86c7', '\u9a6c', '\u7f8a', '\u7334', '\u9e21', '\u72d7', '\u732a'],
/**
* 24节气速查表
* @Array Of Property
* @trans["小寒","大寒","立春","雨水","惊蛰","春分","清明","谷雨","立夏","小满","芒种","夏至","小暑","大暑","立秋","处暑","白露","秋分","寒露","霜降","立冬","小雪","大雪","冬至"]
* @return Cn string
*/
solarTerm: ['\u5c0f\u5bd2', '\u5927\u5bd2', '\u7acb\u6625', '\u96e8\u6c34', '\u60ca\u86f0', '\u6625\u5206', '\u6e05\u660e', '\u8c37\u96e8', '\u7acb\u590f', '\u5c0f\u6ee1', '\u8292\u79cd', '\u590f\u81f3', '\u5c0f\u6691', '\u5927\u6691', '\u7acb\u79cb', '\u5904\u6691', '\u767d\u9732', '\u79cb\u5206', '\u5bd2\u9732', '\u971c\u964d', '\u7acb\u51ac', '\u5c0f\u96ea', '\u5927\u96ea', '\u51ac\u81f3'],
/**
* 1900-2100各年的24节气日期速查表
* @Array Of Property
* @return 0x string For splice
*/
sTermInfo: ['9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf97c3598082c95f8c965cc920f',
'97bd0b06bdb0722c965ce1cfcc920f', 'b027097bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e',
'97bcf97c359801ec95f8c965cc920f', '97bd0b06bdb0722c965ce1cfcc920f', 'b027097bd097c36b0b6fc9274c91aa',
'97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f', '97bd0b06bdb0722c965ce1cfcc920f',
'b027097bd097c36b0b6fc9274c91aa', '9778397bd19801ec9210c965cc920e', '97b6b97bd19801ec95f8c965cc920f',
'97bd09801d98082c95f8e1cfcc920f', '97bd097bd097c36b0b6fc9210c8dc2', '9778397bd197c36c9210c9274c91aa',
'97b6b97bd19801ec95f8c965cc920e', '97bd09801d98082c95f8e1cfcc920f', '97bd097bd097c36b0b6fc9210c8dc2',
'9778397bd097c36c9210c9274c91aa', '97b6b97bd19801ec95f8c965cc920e', '97bcf97c3598082c95f8e1cfcc920f',
'97bd097bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c91aa', '97b6b97bd19801ec9210c965cc920e',
'97bcf97c3598082c95f8c965cc920f', '97bd097bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa',
'97b6b97bd19801ec9210c965cc920e', '97bcf97c3598082c95f8c965cc920f', '97bd097bd097c35b0b6fc920fb0722',
'9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f',
'97bd097bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e',
'97bcf97c359801ec95f8c965cc920f', '97bd097bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa',
'97b6b97bd19801ec9210c965cc920e', '97bcf97c359801ec95f8c965cc920f', '97bd097bd07f595b0b6fc920fb0722',
'9778397bd097c36b0b6fc9210c8dc2', '9778397bd19801ec9210c9274c920e', '97b6b97bd19801ec95f8c965cc920f',
'97bd07f5307f595b0b0bc920fb0722', '7f0e397bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c920e',
'97b6b97bd19801ec95f8c965cc920f', '97bd07f5307f595b0b0bc920fb0722', '7f0e397bd097c36b0b6fc9210c8dc2',
'9778397bd097c36c9210c9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bd07f1487f595b0b0bc920fb0722',
'7f0e397bd097c36b0b6fc9210c8dc2', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e',
'97bcf7f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa',
'97b6b97bd19801ec9210c965cc920e', '97bcf7f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722',
'9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e', '97bcf7f1487f531b0b0bb0b6fb0722',
'7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b97bd19801ec9210c965cc920e',
'97bcf7f1487f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa',
'97b6b97bd19801ec9210c9274c920e', '97bcf7f0e47f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722',
'9778397bd097c36b0b6fc9210c91aa', '97b6b97bd197c36c9210c9274c920e', '97bcf7f0e47f531b0b0bb0b6fb0722',
'7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9210c8dc2', '9778397bd097c36c9210c9274c920e',
'97b6b7f0e47f531b0723b0b6fb0722', '7f0e37f5307f595b0b0bc920fb0722', '7f0e397bd097c36b0b6fc9210c8dc2',
'9778397bd097c36b0b70c9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721', '7f0e37f1487f595b0b0bb0b6fb0722',
'7f0e397bd097c35b0b6fc9210c8dc2', '9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721',
'7f0e27f1487f595b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa',
'97b6b7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722',
'9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722',
'7f0e397bd097c35b0b6fc920fb0722', '9778397bd097c36b0b6fc9274c91aa', '97b6b7f0e47f531b0723b0b6fb0721',
'7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9274c91aa',
'97b6b7f0e47f531b0723b0787b0721', '7f0e27f0e47f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722',
'9778397bd097c36b0b6fc9210c91aa', '97b6b7f0e47f149b0723b0787b0721', '7f0e27f0e47f531b0723b0b6fb0722',
'7f0e397bd07f595b0b0bc920fb0722', '9778397bd097c36b0b6fc9210c8dc2', '977837f0e37f149b0723b0787b0721',
'7f07e7f0e47f531b0723b0b6fb0722', '7f0e37f5307f595b0b0bc920fb0722', '7f0e397bd097c35b0b6fc9210c8dc2',
'977837f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e37f1487f595b0b0bb0b6fb0722',
'7f0e397bd097c35b0b6fc9210c8dc2', '977837f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721',
'7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722', '977837f0e37f14998082b0787b06bd',
'7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd097c35b0b6fc920fb0722',
'977837f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722',
'7f0e397bd07f595b0b0bc920fb0722', '977837f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721',
'7f0e27f1487f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722', '977837f0e37f14998082b0787b06bd',
'7f07e7f0e47f149b0723b0787b0721', '7f0e27f0e47f531b0b0bb0b6fb0722', '7f0e397bd07f595b0b0bc920fb0722',
'977837f0e37f14998082b0723b06bd', '7f07e7f0e37f149b0723b0787b0721', '7f0e27f0e47f531b0723b0b6fb0722',
'7f0e397bd07f595b0b0bc920fb0722', '977837f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b0721',
'7f07e7f0e47f531b0723b0b6fb0722', '7f0e37f1487f595b0b0bb0b6fb0722', '7f0e37f0e37f14898082b0723b02d5',
'7ec967f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0722', '7f0e37f1487f531b0b0bb0b6fb0722',
'7f0e37f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721',
'7f0e37f1487f531b0b0bb0b6fb0722', '7f0e37f0e37f14898082b072297c35', '7ec967f0e37f14998082b0787b06bd',
'7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722', '7f0e37f0e37f14898082b072297c35',
'7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722',
'7f0e37f0e366aa89801eb072297c35', '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f149b0723b0787b0721',
'7f0e27f1487f531b0b0bb0b6fb0722', '7f0e37f0e366aa89801eb072297c35', '7ec967f0e37f14998082b0723b06bd',
'7f07e7f0e47f149b0723b0787b0721', '7f0e27f0e47f531b0723b0b6fb0722', '7f0e37f0e366aa89801eb072297c35',
'7ec967f0e37f14998082b0723b06bd', '7f07e7f0e37f14998083b0787b0721', '7f0e27f0e47f531b0723b0b6fb0722',
'7f0e37f0e366aa89801eb072297c35', '7ec967f0e37f14898082b0723b02d5', '7f07e7f0e37f14998082b0787b0721',
'7f07e7f0e47f531b0723b0b6fb0722', '7f0e36665b66aa89801e9808297c35', '665f67f0e37f14898082b0723b02d5',
'7ec967f0e37f14998082b0787b0721', '7f07e7f0e47f531b0723b0b6fb0722', '7f0e36665b66a449801e9808297c35',
'665f67f0e37f14898082b0723b02d5', '7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721',
'7f0e36665b66a449801e9808297c35', '665f67f0e37f14898082b072297c35', '7ec967f0e37f14998082b0787b06bd',
'7f07e7f0e47f531b0723b0b6fb0721', '7f0e26665b66a449801e9808297c35', '665f67f0e37f1489801eb072297c35',
'7ec967f0e37f14998082b0787b06bd', '7f07e7f0e47f531b0723b0b6fb0721', '7f0e27f1487f531b0b0bb0b6fb0722'],
/**
* 数字转中文速查表
* @Array Of Property
* @trans ['日','一','二','三','四','五','六','七','八','九','十']
* @return Cn string
*/
nStr1: ['\u65e5', '\u4e00', '\u4e8c', '\u4e09', '\u56db', '\u4e94', '\u516d', '\u4e03', '\u516b', '\u4e5d', '\u5341'],
/**
* 日期转农历称呼速查表
* @Array Of Property
* @trans ['初','十','廿','卅']
* @return Cn string
*/
nStr2: ['\u521d', '\u5341', '\u5eff', '\u5345'],
/**
* 月份转农历称呼速查表
* @Array Of Property
* @trans ['正','一','二','三','四','五','六','七','八','九','十','冬','腊']
* @return Cn string
*/
nStr3: ['\u6b63', '\u4e8c', '\u4e09', '\u56db', '\u4e94', '\u516d', '\u4e03', '\u516b', '\u4e5d', '\u5341', '\u51ac', '\u814a'],
/**
* 返回农历y年一整年的总天数
* @param lunar Year
* @return Number
* @eg:var count = calendar.lYearDays(1987) ;//count=387
*/
lYearDays: function (y) {
var i; var sum = 348
for (i = 0x8000; i > 0x8; i >>= 1) { sum += (this.lunarInfo[y - 1900] & i) ? 1 : 0 }
return (sum + this.leapDays(y))
},
/**
* 返回农历y年闰月是哪个月;若y年没有闰月 则返回0
* @param lunar Year
* @return Number (0-12)
* @eg:var leapMonth = calendar.leapMonth(1987) ;//leapMonth=6
*/
leapMonth: function (y) { // 闰字编码 \u95f0
return (this.lunarInfo[y - 1900] & 0xf)
},
/**
* 返回农历y年闰月的天数 若该年没有闰月则返回0
* @param lunar Year
* @return Number (0、29、30)
* @eg:var leapMonthDay = calendar.leapDays(1987) ;//leapMonthDay=29
*/
leapDays: function (y) {
if (this.leapMonth(y)) {
return ((this.lunarInfo[y - 1900] & 0x10000) ? 30 : 29)
}
return (0)
},
/**
* 返回农历y年m月(非闰月)的总天数,计算m为闰月时的天数请使用leapDays方法
* @param lunar Year
* @return Number (-1、29、30)
* @eg:var MonthDay = calendar.monthDays(1987,9) ;//MonthDay=29
*/
monthDays: function (y, m) {
if (m > 12 || m < 1) { return -1 }// 月份参数从1至12,参数错误返回-1
return ((this.lunarInfo[y - 1900] & (0x10000 >> m)) ? 30 : 29)
},
/**
* 返回公历(!)y年m月的天数
* @param solar Year
* @return Number (-1、28、29、30、31)
* @eg:var solarMonthDay = calendar.leapDays(1987) ;//solarMonthDay=30
*/
solarDays: function (y, m) {
if (m > 12 || m < 1) { return -1 } // 若参数错误 返回-1
var ms = m - 1
if (ms == 1) { // 2月份的闰平规律测算后确认返回28或29
return (((y % 4 == 0) && (y % 100 != 0) || (y % 400 == 0)) ? 29 : 28)
} else {
return (this.solarMonth[ms])
}
},
/**
* 农历年份转换为干支纪年
* @param lYear 农历年的年份数
* @return Cn string
*/
toGanZhiYear: function (lYear) {
var ganKey = (lYear - 3) % 10
var zhiKey = (lYear - 3) % 12
if (ganKey == 0) ganKey = 10// 如果余数为0则为最后一个天干
if (zhiKey == 0) zhiKey = 12// 如果余数为0则为最后一个地支
return this.Gan[ganKey - 1] + this.Zhi[zhiKey - 1]
},
/**
* 公历月、日判断所属星座
* @param cMonth [description]
* @param cDay [description]
* @return Cn string
*/
toAstro: function (cMonth, cDay) {
var s = '\u9b54\u7faf\u6c34\u74f6\u53cc\u9c7c\u767d\u7f8a\u91d1\u725b\u53cc\u5b50\u5de8\u87f9\u72ee\u5b50\u5904\u5973\u5929\u79e4\u5929\u874e\u5c04\u624b\u9b54\u7faf'
var arr = [20, 19, 21, 21, 21, 22, 23, 23, 23, 23, 22, 22]
return s.substr(cMonth * 2 - (cDay < arr[cMonth - 1] ? 2 : 0), 2) + '\u5ea7'// 座
},
/**
* 传入offset偏移量返回干支
* @param offset 相对甲子的偏移量
* @return Cn string
*/
toGanZhi: function (offset) {
return this.Gan[offset % 10] + this.Zhi[offset % 12]
},
/**
* 传入公历(!)y年获得该年第n个节气的公历日期
* @param y公历年(1900-2100);n二十四节气中的第几个节气(1~24);从n=1(小寒)算起
* @return day Number
* @eg:var _24 = calendar.getTerm(1987,3) ;//_24=4;意即1987年2月4日立春
*/
getTerm: function (y, n) {
if (y < 1900 || y > 2100) { return -1 }
if (n < 1 || n > 24) { return -1 }
var _table = this.sTermInfo[y - 1900]
var _info = [
parseInt('0x' + _table.substr(0, 5)).toString(),
parseInt('0x' + _table.substr(5, 5)).toString(),
parseInt('0x' + _table.substr(10, 5)).toString(),
parseInt('0x' + _table.substr(15, 5)).toString(),
parseInt('0x' + _table.substr(20, 5)).toString(),
parseInt('0x' + _table.substr(25, 5)).toString()
]
var _calday = [
_info[0].substr(0, 1),
_info[0].substr(1, 2),
_info[0].substr(3, 1),
_info[0].substr(4, 2),
_info[1].substr(0, 1),
_info[1].substr(1, 2),
_info[1].substr(3, 1),
_info[1].substr(4, 2),
_info[2].substr(0, 1),
_info[2].substr(1, 2),
_info[2].substr(3, 1),
_info[2].substr(4, 2),
_info[3].substr(0, 1),
_info[3].substr(1, 2),
_info[3].substr(3, 1),
_info[3].substr(4, 2),
_info[4].substr(0, 1),
_info[4].substr(1, 2),
_info[4].substr(3, 1),
_info[4].substr(4, 2),
_info[5].substr(0, 1),
_info[5].substr(1, 2),
_info[5].substr(3, 1),
_info[5].substr(4, 2)
]
return parseInt(_calday[n - 1])
},
/**
* 传入农历数字月份返回汉语通俗表示法
* @param lunar month
* @return Cn string
* @eg:var cnMonth = calendar.toChinaMonth(12) ;//cnMonth='腊月'
*/
toChinaMonth: function (m) { // 月 => \u6708
if (m > 12 || m < 1) { return -1 } // 若参数错误 返回-1
var s = this.nStr3[m - 1]
s += '\u6708'// 加上月字
return s
},
/**
* 传入农历日期数字返回汉字表示法
* @param lunar day
* @return Cn string
* @eg:var cnDay = calendar.toChinaDay(21) ;//cnMonth='廿一'
*/
toChinaDay: function (d) { // 日 => \u65e5
var s
switch (d) {
case 10:
s = '\u521d\u5341'; break
case 20:
s = '\u4e8c\u5341'; break
break
case 30:
s = '\u4e09\u5341'; break
break
default :
s = this.nStr2[Math.floor(d / 10)]
s += this.nStr1[d % 10]
}
return (s)
},
/**
* 年份转生肖[!仅能大致转换] => 精确划分生肖分界线是“立春”
* @param y year
* @return Cn string
* @eg:var animal = calendar.getAnimal(1987) ;//animal='兔'
*/
getAnimal: function (y) {
return this.Animals[(y - 4) % 12]
},
/**
* 传入阳历年月日获得详细的公历、农历object信息 <=>JSON
* @param y solar year
* @param m solar month
* @param d solar day
* @return JSON object
* @eg:console.log(calendar.solar2lunar(1987,11,01));
*/
solar2lunar: function (y, m, d) { // 参数区间1900.1.31~2100.12.31
// 年份限定、上限
if (y < 1900 || y > 2100) {
return -1// undefined转换为数字变为NaN
}
// 公历传参最下限
if (y == 1900 && m == 1 && d < 31) {
return -1
}
// 未传参 获得当天
if (!y) {
var objDate = new Date()
} else {
var objDate = new Date(y, parseInt(m) - 1, d)
}
var i; var leap = 0; var temp = 0
// 修正ymd参数
var y = objDate.getFullYear()
var m = objDate.getMonth() + 1
var d = objDate.getDate()
var offset = (Date.UTC(objDate.getFullYear(), objDate.getMonth(), objDate.getDate()) - Date.UTC(1900, 0, 31)) / 86400000
for (i = 1900; i < 2101 && offset > 0; i++) {
temp = this.lYearDays(i)
offset -= temp
}
if (offset < 0) {
offset += temp; i--
}
// 是否今天
var isTodayObj = new Date()
var isToday = false
if (isTodayObj.getFullYear() == y && isTodayObj.getMonth() + 1 == m && isTodayObj.getDate() == d) {
isToday = true
}
// 星期几
var nWeek = objDate.getDay()
var cWeek = this.nStr1[nWeek]
// 数字表示周几顺应天朝周一开始的惯例
if (nWeek == 0) {
nWeek = 7
}
// 农历年
var year = i
var leap = this.leapMonth(i) // 闰哪个月
var isLeap = false
// 效验闰月
for (i = 1; i < 13 && offset > 0; i++) {
// 闰月
if (leap > 0 && i == (leap + 1) && isLeap == false) {
--i
isLeap = true; temp = this.leapDays(year) // 计算农历闰月天数
} else {
temp = this.monthDays(year, i)// 计算农历普通月天数
}
// 解除闰月
if (isLeap == true && i == (leap + 1)) { isLeap = false }
offset -= temp
}
// 闰月导致数组下标重叠取反
if (offset == 0 && leap > 0 && i == leap + 1) {
if (isLeap) {
isLeap = false
} else {
isLeap = true; --i
}
}
if (offset < 0) {
offset += temp; --i
}
// 农历月
var month = i
// 农历日
var day = offset + 1
// 天干地支处理
var sm = m - 1
var gzY = this.toGanZhiYear(year)
// 当月的两个节气
// bugfix-2017-7-24 11:03:38 use lunar Year Param `y` Not `year`
var firstNode = this.getTerm(y, (m * 2 - 1))// 返回当月「节」为几日开始
var secondNode = this.getTerm(y, (m * 2))// 返回当月「节」为几日开始
// 依据12节气修正干支月
var gzM = this.toGanZhi((y - 1900) * 12 + m + 11)
if (d >= firstNode) {
gzM = this.toGanZhi((y - 1900) * 12 + m + 12)
}
// 传入的日期的节气与否
var isTerm = false
var Term = null
if (firstNode == d) {
isTerm = true
Term = this.solarTerm[m * 2 - 2]
}
if (secondNode == d) {
isTerm = true
Term = this.solarTerm[m * 2 - 1]
}
// 日柱 当月一日与 1900/1/1 相差天数
var dayCyclical = Date.UTC(y, sm, 1, 0, 0, 0, 0) / 86400000 + 25567 + 10
var gzD = this.toGanZhi(dayCyclical + d - 1)
// 该日期所属的星座
var astro = this.toAstro(m, d)
return { 'lYear': year, 'lMonth': month, 'lDay': day, 'Animal': this.getAnimal(year), 'IMonthCn': (isLeap ? '\u95f0' : '') + this.toChinaMonth(month), 'IDayCn': this.toChinaDay(day), 'cYear': y, 'cMonth': m, 'cDay': d, 'gzYear': gzY, 'gzMonth': gzM, 'gzDay': gzD, 'isToday': isToday, 'isLeap': isLeap, 'nWeek': nWeek, 'ncWeek': '\u661f\u671f' + cWeek, 'isTerm': isTerm, 'Term': Term, 'astro': astro }
},
/**
* 传入农历年月日以及传入的月份是否闰月获得详细的公历、农历object信息 <=>JSON
* @param y lunar year
* @param m lunar month
* @param d lunar day
* @param isLeapMonth lunar month is leap or not.[如果是农历闰月第四个参数赋值true即可]
* @return JSON object
* @eg:console.log(calendar.lunar2solar(1987,9,10));
*/
lunar2solar: function (y, m, d, isLeapMonth) { // 参数区间1900.1.31~2100.12.1
var isLeapMonth = !!isLeapMonth
var leapOffset = 0
var leapMonth = this.leapMonth(y)
var leapDay = this.leapDays(y)
if (isLeapMonth && (leapMonth != m)) { return -1 }// 传参要求计算该闰月公历 但该年得出的闰月与传参的月份并不同
if (y == 2100 && m == 12 && d > 1 || y == 1900 && m == 1 && d < 31) { return -1 }// 超出了最大极限值
var day = this.monthDays(y, m)
var _day = day
// bugFix 2016-9-25
// if month is leap, _day use leapDays method
if (isLeapMonth) {
_day = this.leapDays(y, m)
}
if (y < 1900 || y > 2100 || d > _day) { return -1 }// 参数合法性效验
// 计算农历的时间差
var offset = 0
for (var i = 1900; i < y; i++) {
offset += this.lYearDays(i)
}
var leap = 0; var isAdd = false
for (var i = 1; i < m; i++) {
leap = this.leapMonth(y)
if (!isAdd) { // 处理闰月
if (leap <= i && leap > 0) {
offset += this.leapDays(y); isAdd = true
}
}
offset += this.monthDays(y, i)
}
// 转换闰月农历 需补充该年闰月的前一个月的时差
if (isLeapMonth) { offset += day }
// 1900年农历正月一日的公历时间为1900年1月30日0时0分0秒(该时间也是本农历的最开始起始点)
var stmap = Date.UTC(1900, 1, 30, 0, 0, 0)
var calObj = new Date((offset + d - 31) * 86400000 + stmap)
var cY = calObj.getUTCFullYear()
var cM = calObj.getUTCMonth() + 1
var cD = calObj.getUTCDate()
return this.solar2lunar(cY, cM, cD)
}
}
export default calendar
@@ -0,0 +1,12 @@
{
"uni-calender.ok": "ok",
"uni-calender.cancel": "cancel",
"uni-calender.today": "today",
"uni-calender.MON": "MON",
"uni-calender.TUE": "TUE",
"uni-calender.WED": "WED",
"uni-calender.THU": "THU",
"uni-calender.FRI": "FRI",
"uni-calender.SAT": "SAT",
"uni-calender.SUN": "SUN"
}
@@ -0,0 +1,8 @@
import en from './en.json'
import zhHans from './zh-Hans.json'
import zhHant from './zh-Hant.json'
export default {
en,
'zh-Hans': zhHans,
'zh-Hant': zhHant
}
@@ -0,0 +1,12 @@
{
"uni-calender.ok": "确定",
"uni-calender.cancel": "取消",
"uni-calender.today": "今日",
"uni-calender.SUN": "日",
"uni-calender.MON": "一",
"uni-calender.TUE": "二",
"uni-calender.WED": "三",
"uni-calender.THU": "四",
"uni-calender.FRI": "五",
"uni-calender.SAT": "六"
}
@@ -0,0 +1,12 @@
{
"uni-calender.ok": "確定",
"uni-calender.cancel": "取消",
"uni-calender.today": "今日",
"uni-calender.SUN": "日",
"uni-calender.MON": "一",
"uni-calender.TUE": "二",
"uni-calender.WED": "三",
"uni-calender.THU": "四",
"uni-calender.FRI": "五",
"uni-calender.SAT": "六"
}
@@ -0,0 +1,187 @@
<template>
<view class="uni-calendar-item__weeks-box" :class="{
'uni-calendar-item--disable':weeks.disable,
'uni-calendar-item--isDay':calendar.fullDate === weeks.fullDate && weeks.isDay,
'uni-calendar-item--checked':(calendar.fullDate === weeks.fullDate && !weeks.isDay) ,
'uni-calendar-item--before-checked':weeks.beforeMultiple,
'uni-calendar-item--multiple': weeks.multiple,
'uni-calendar-item--after-checked':weeks.afterMultiple,
}"
@click="choiceDate(weeks)">
<view class="uni-calendar-item__weeks-box-item">
<text v-if="selected&&weeks.extraInfo" class="uni-calendar-item__weeks-box-circle"></text>
<text class="uni-calendar-item__weeks-box-text" :class="{
'uni-calendar-item--isDay-text': weeks.isDay,
'uni-calendar-item--isDay':calendar.fullDate === weeks.fullDate && weeks.isDay,
'uni-calendar-item--checked':calendar.fullDate === weeks.fullDate && !weeks.isDay,
'uni-calendar-item--before-checked':weeks.beforeMultiple,
'uni-calendar-item--multiple': weeks.multiple,
'uni-calendar-item--after-checked':weeks.afterMultiple,
'uni-calendar-item--disable':weeks.disable,
}">{{weeks.date}}</text>
<text v-if="!lunar&&!weeks.extraInfo && weeks.isDay" class="uni-calendar-item__weeks-lunar-text" :class="{
'uni-calendar-item--isDay-text':weeks.isDay,
'uni-calendar-item--isDay':calendar.fullDate === weeks.fullDate && weeks.isDay,
'uni-calendar-item--checked':calendar.fullDate === weeks.fullDate && !weeks.isDay,
'uni-calendar-item--before-checked':weeks.beforeMultiple,
'uni-calendar-item--multiple': weeks.multiple,
'uni-calendar-item--after-checked':weeks.afterMultiple,
}">{{todayText}}</text>
<text v-if="lunar&&!weeks.extraInfo" class="uni-calendar-item__weeks-lunar-text" :class="{
'uni-calendar-item--isDay-text':weeks.isDay,
'uni-calendar-item--isDay':calendar.fullDate === weeks.fullDate && weeks.isDay,
'uni-calendar-item--checked':calendar.fullDate === weeks.fullDate && !weeks.isDay,
'uni-calendar-item--before-checked':weeks.beforeMultiple,
'uni-calendar-item--multiple': weeks.multiple,
'uni-calendar-item--after-checked':weeks.afterMultiple,
'uni-calendar-item--disable':weeks.disable,
}">{{weeks.isDay ? todayText : (weeks.lunar.IDayCn === '初一'?weeks.lunar.IMonthCn:weeks.lunar.IDayCn)}}</text>
<text v-if="weeks.extraInfo&&weeks.extraInfo.info" class="uni-calendar-item__weeks-lunar-text" :class="{
'uni-calendar-item--extra':weeks.extraInfo.info,
'uni-calendar-item--isDay-text':weeks.isDay,
'uni-calendar-item--isDay':calendar.fullDate === weeks.fullDate && weeks.isDay,
'uni-calendar-item--checked':calendar.fullDate === weeks.fullDate && !weeks.isDay,
'uni-calendar-item--before-checked':weeks.beforeMultiple,
'uni-calendar-item--multiple': weeks.multiple,
'uni-calendar-item--after-checked':weeks.afterMultiple,
'uni-calendar-item--disable':weeks.disable,
}">{{weeks.extraInfo.info}}</text>
</view>
</view>
</template>
<script>
import { initVueI18n } from '@dcloudio/uni-i18n'
import i18nMessages from './i18n/index.js'
const { t } = initVueI18n(i18nMessages)
export default {
emits:['change'],
props: {
weeks: {
type: Object,
default () {
return {}
}
},
calendar: {
type: Object,
default: () => {
return {}
}
},
selected: {
type: Array,
default: () => {
return []
}
},
lunar: {
type: Boolean,
default: false
}
},
computed: {
todayText() {
return t("uni-calender.today")
},
},
methods: {
choiceDate(weeks) {
this.$emit('change', weeks)
}
}
}
</script>
<style lang="scss" scoped>
$uni-font-size-base:14px;
$uni-text-color:#333;
$uni-font-size-sm:12px;
$uni-color-error: #e43d33;
$uni-opacity-disabled: 0.3;
$uni-text-color-disable:#c0c0c0;
$uni-primary: #2979ff !default;
.uni-calendar-item__weeks-box {
flex: 1;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
justify-content: center;
align-items: center;
}
.uni-calendar-item__weeks-box-text {
font-size: $uni-font-size-base;
color: $uni-text-color;
}
.uni-calendar-item__weeks-lunar-text {
font-size: $uni-font-size-sm;
color: $uni-text-color;
}
.uni-calendar-item__weeks-box-item {
position: relative;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
justify-content: center;
align-items: center;
width: 100rpx;
height: 100rpx;
}
.uni-calendar-item__weeks-box-circle {
position: absolute;
top: 5px;
right: 5px;
width: 8px;
height: 8px;
border-radius: 8px;
background-color: $uni-color-error;
}
.uni-calendar-item--disable {
background-color: rgba(249, 249, 249, $uni-opacity-disabled);
color: $uni-text-color-disable;
}
.uni-calendar-item--isDay-text {
color: $uni-primary;
}
.uni-calendar-item--isDay {
background-color: $uni-primary;
opacity: 0.8;
color: #fff;
}
.uni-calendar-item--extra {
color: $uni-color-error;
opacity: 0.8;
}
.uni-calendar-item--checked {
background-color: $uni-primary;
color: #fff;
opacity: 0.8;
}
.uni-calendar-item--multiple {
background-color: $uni-primary;
color: #fff;
opacity: 0.8;
}
.uni-calendar-item--before-checked {
background-color: #ff5a5f;
color: #fff;
}
.uni-calendar-item--after-checked {
background-color: #ff5a5f;
color: #fff;
}
</style>
@@ -0,0 +1,567 @@
<template>
<view class="uni-calendar">
<view v-if="!insert&&show" class="uni-calendar__mask" :class="{'uni-calendar--mask-show':aniMaskShow}" @click="clean"></view>
<view v-if="insert || show" class="uni-calendar__content" :class="{'uni-calendar--fixed':!insert,'uni-calendar--ani-show':aniMaskShow}">
<view v-if="!insert" class="uni-calendar__header uni-calendar--fixed-top">
<view class="uni-calendar__header-btn-box" @click="close">
<text class="uni-calendar__header-text uni-calendar--fixed-width">{{cancelText}}</text>
</view>
<view class="uni-calendar__header-btn-box" @click="confirm">
<text class="uni-calendar__header-text uni-calendar--fixed-width">{{okText}}</text>
</view>
</view>
<view class="uni-calendar__header">
<view class="uni-calendar__header-btn-box" @click.stop="pre">
<view class="uni-calendar__header-btn uni-calendar--left"></view>
</view>
<picker mode="date" :value="date" fields="month" @change="bindDateChange">
<text class="uni-calendar__header-text">{{ (nowDate.year||'') +' / '+( nowDate.month||'')}}</text>
</picker>
<view class="uni-calendar__header-btn-box" @click.stop="next">
<view class="uni-calendar__header-btn uni-calendar--right"></view>
</view>
<text class="uni-calendar__backtoday" @click="backToday">{{todayText}}</text>
</view>
<view class="uni-calendar__box">
<view v-if="showMonth" class="uni-calendar__box-bg">
<text class="uni-calendar__box-bg-text">{{nowDate.month}}</text>
</view>
<view class="uni-calendar__weeks">
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{SUNText}}</text>
</view>
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{monText}}</text>
</view>
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{TUEText}}</text>
</view>
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{WEDText}}</text>
</view>
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{THUText}}</text>
</view>
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{FRIText}}</text>
</view>
<view class="uni-calendar__weeks-day">
<text class="uni-calendar__weeks-day-text">{{SATText}}</text>
</view>
</view>
<view class="uni-calendar__weeks" v-for="(item,weekIndex) in weeks" :key="weekIndex">
<view class="uni-calendar__weeks-item" v-for="(weeks,weeksIndex) in item" :key="weeksIndex">
<calendar-item class="uni-calendar-item--hook" :weeks="weeks" :calendar="calendar" :selected="selected" :lunar="lunar" @change="choiceDate"></calendar-item>
</view>
</view>
</view>
</view>
</view>
</template>
<script>
import Calendar from './util.js';
import CalendarItem from './uni-calendar-item.vue'
import { initVueI18n } from '@dcloudio/uni-i18n'
import i18nMessages from './i18n/index.js'
const { t } = initVueI18n(i18nMessages)
/**
* Calendar 日历
* @description 日历组件可以查看日期,选择任意范围内的日期,打点操作。常用场景如:酒店日期预订、火车机票选择购买日期、上下班打卡等
* @tutorial https://ext.dcloud.net.cn/plugin?id=56
* @property {String} date 自定义当前时间,默认为今天
* @property {Boolean} lunar 显示农历
* @property {String} startDate 日期选择范围-开始日期
* @property {String} endDate 日期选择范围-结束日期
* @property {Boolean} range 范围选择
* @property {Boolean} insert = [true|false] 插入模式,默认为false
* @value true 弹窗模式
* @value false 插入模式
* @property {Boolean} clearDate = [true|false] 弹窗模式是否清空上次选择内容
* @property {Array} selected 打点,期待格式[{date: '2019-06-27', info: '签到', data: { custom: '自定义信息', name: '自定义消息头',xxx:xxx... }}]
* @property {Boolean} showMonth 是否选择月份为背景
* @event {Function} change 日期改变,`insert :ture` 时生效
* @event {Function} confirm 确认选择`insert :false` 时生效
* @event {Function} monthSwitch 切换月份时触发
* @example <uni-calendar :insert="true":lunar="true" :start-date="'2019-3-2'":end-date="'2019-5-20'"@change="change" />
*/
export default {
components: {
CalendarItem
},
emits:['close','confirm','change','monthSwitch'],
props: {
date: {
type: String,
default: ''
},
selected: {
type: Array,
default () {
return []
}
},
lunar: {
type: Boolean,
default: false
},
startDate: {
type: String,
default: ''
},
endDate: {
type: String,
default: ''
},
range: {
type: Boolean,
default: false
},
insert: {
type: Boolean,
default: true
},
showMonth: {
type: Boolean,
default: true
},
clearDate: {
type: Boolean,
default: true
}
},
data() {
return {
show: false,
weeks: [],
calendar: {},
nowDate: '',
aniMaskShow: false
}
},
computed:{
/**
* for i18n
*/
okText() {
return t("uni-calender.ok")
},
cancelText() {
return t("uni-calender.cancel")
},
todayText() {
return t("uni-calender.today")
},
monText() {
return t("uni-calender.MON")
},
TUEText() {
return t("uni-calender.TUE")
},
WEDText() {
return t("uni-calender.WED")
},
THUText() {
return t("uni-calender.THU")
},
FRIText() {
return t("uni-calender.FRI")
},
SATText() {
return t("uni-calender.SAT")
},
SUNText() {
return t("uni-calender.SUN")
},
},
watch: {
date(newVal) {
// this.cale.setDate(newVal)
this.init(newVal)
},
startDate(val){
this.cale.resetSatrtDate(val)
this.cale.setDate(this.nowDate.fullDate)
this.weeks = this.cale.weeks
},
endDate(val){
this.cale.resetEndDate(val)
this.cale.setDate(this.nowDate.fullDate)
this.weeks = this.cale.weeks
},
selected(newVal) {
this.cale.setSelectInfo(this.nowDate.fullDate, newVal)
this.weeks = this.cale.weeks
}
},
created() {
this.cale = new Calendar({
selected: this.selected,
startDate: this.startDate,
endDate: this.endDate,
range: this.range,
})
this.init(this.date)
},
methods: {
// 取消穿透
clean() {},
bindDateChange(e) {
const value = e.detail.value + '-1'
this.setDate(value)
const { year,month } = this.cale.getDate(value)
this.$emit('monthSwitch', {
year,
month
})
},
/**
* 初始化日期显示
* @param {Object} date
*/
init(date) {
this.cale.setDate(date)
this.weeks = this.cale.weeks
this.nowDate = this.calendar = this.cale.getInfo(date)
},
/**
* 打开日历弹窗
*/
open() {
// 弹窗模式并且清理数据
if (this.clearDate && !this.insert) {
this.cale.cleanMultipleStatus()
// this.cale.setDate(this.date)
this.init(this.date)
}
this.show = true
this.$nextTick(() => {
setTimeout(() => {
this.aniMaskShow = true
}, 50)
})
},
/**
* 关闭日历弹窗
*/
close() {
this.aniMaskShow = false
this.$nextTick(() => {
setTimeout(() => {
this.show = false
this.$emit('close')
}, 300)
})
},
/**
* 确认按钮
*/
confirm() {
this.setEmit('confirm')
this.close()
},
/**
* 变化触发
*/
change() {
if (!this.insert) return
this.setEmit('change')
},
/**
* 选择月份触发
*/
monthSwitch() {
let {
year,
month
} = this.nowDate
this.$emit('monthSwitch', {
year,
month: Number(month)
})
},
/**
* 派发事件
* @param {Object} name
*/
setEmit(name) {
let {
year,
month,
date,
fullDate,
lunar,
extraInfo
} = this.calendar
this.$emit(name, {
range: this.cale.multipleStatus,
year,
month,
date,
fulldate: fullDate,
lunar,
extraInfo: extraInfo || {}
})
},
/**
* 选择天触发
* @param {Object} weeks
*/
choiceDate(weeks) {
if (weeks.disable) return
this.calendar = weeks
// 设置多选
this.cale.setMultiple(this.calendar.fullDate)
this.weeks = this.cale.weeks
this.change()
},
/**
* 回到今天
*/
backToday() {
const nowYearMonth = `${this.nowDate.year}-${this.nowDate.month}`
const date = this.cale.getDate(new Date())
const todayYearMonth = `${date.year}-${date.month}`
this.init(date.fullDate)
if(nowYearMonth !== todayYearMonth) {
this.monthSwitch()
}
this.change()
},
/**
* 上个月
*/
pre() {
const preDate = this.cale.getDate(this.nowDate.fullDate, -1, 'month').fullDate
this.setDate(preDate)
this.monthSwitch()
},
/**
* 下个月
*/
next() {
const nextDate = this.cale.getDate(this.nowDate.fullDate, +1, 'month').fullDate
this.setDate(nextDate)
this.monthSwitch()
},
/**
* 设置日期
* @param {Object} date
*/
setDate(date) {
this.cale.setDate(date)
this.weeks = this.cale.weeks
this.nowDate = this.cale.getInfo(date)
}
}
}
</script>
<style lang="scss" scoped>
$uni-bg-color-mask: rgba($color: #000000, $alpha: 0.4);
$uni-border-color: #EDEDED;
$uni-text-color: #333;
$uni-bg-color-hover:#f1f1f1;
$uni-font-size-base:14px;
$uni-text-color-placeholder: #808080;
$uni-color-subtitle: #555555;
$uni-text-color-grey:#999;
.uni-calendar {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
}
.uni-calendar__mask {
position: fixed;
bottom: 0;
top: 0;
left: 0;
right: 0;
background-color: $uni-bg-color-mask;
transition-property: opacity;
transition-duration: 0.3s;
opacity: 0;
/* #ifndef APP-NVUE */
z-index: 99;
/* #endif */
}
.uni-calendar--mask-show {
opacity: 1
}
.uni-calendar--fixed {
position: fixed;
/* #ifdef APP-NVUE */
bottom: 0;
/* #endif */
left: 0;
right: 0;
transition-property: transform;
transition-duration: 0.3s;
transform: translateY(460px);
/* #ifndef APP-NVUE */
bottom: calc(var(--window-bottom));
z-index: 99;
/* #endif */
}
.uni-calendar--ani-show {
transform: translateY(0);
}
.uni-calendar__content {
background-color: #fff;
}
.uni-calendar__header {
position: relative;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
justify-content: center;
align-items: center;
height: 50px;
border-bottom-color: $uni-border-color;
border-bottom-style: solid;
border-bottom-width: 1px;
}
.uni-calendar--fixed-top {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
justify-content: space-between;
border-top-color: $uni-border-color;
border-top-style: solid;
border-top-width: 1px;
}
.uni-calendar--fixed-width {
width: 50px;
}
.uni-calendar__backtoday {
position: absolute;
right: 0;
top: 25rpx;
padding: 0 5px;
padding-left: 10px;
height: 25px;
line-height: 25px;
font-size: 12px;
border-top-left-radius: 25px;
border-bottom-left-radius: 25px;
color: $uni-text-color;
background-color: $uni-bg-color-hover;
}
.uni-calendar__header-text {
text-align: center;
width: 100px;
font-size: $uni-font-size-base;
color: $uni-text-color;
}
.uni-calendar__header-btn-box {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
align-items: center;
justify-content: center;
width: 50px;
height: 50px;
}
.uni-calendar__header-btn {
width: 10px;
height: 10px;
border-left-color: $uni-text-color-placeholder;
border-left-style: solid;
border-left-width: 2px;
border-top-color: $uni-color-subtitle;
border-top-style: solid;
border-top-width: 2px;
}
.uni-calendar--left {
transform: rotate(-45deg);
}
.uni-calendar--right {
transform: rotate(135deg);
}
.uni-calendar__weeks {
position: relative;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
}
.uni-calendar__weeks-item {
flex: 1;
}
.uni-calendar__weeks-day {
flex: 1;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
justify-content: center;
align-items: center;
height: 45px;
border-bottom-color: #F5F5F5;
border-bottom-style: solid;
border-bottom-width: 1px;
}
.uni-calendar__weeks-day-text {
font-size: 14px;
}
.uni-calendar__box {
position: relative;
}
.uni-calendar__box-bg {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
justify-content: center;
align-items: center;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
}
.uni-calendar__box-bg-text {
font-size: 200px;
font-weight: bold;
color: $uni-text-color-grey;
opacity: 0.1;
text-align: center;
/* #ifndef APP-NVUE */
line-height: 1;
/* #endif */
}
</style>
@@ -0,0 +1,360 @@
import CALENDAR from './calendar.js'
class Calendar {
constructor({
date,
selected,
startDate,
endDate,
range
} = {}) {
// 当前日期
this.date = this.getDate(new Date()) // 当前初入日期
// 打点信息
this.selected = selected || [];
// 范围开始
this.startDate = startDate
// 范围结束
this.endDate = endDate
this.range = range
// 多选状态
this.cleanMultipleStatus()
// 每周日期
this.weeks = {}
// this._getWeek(this.date.fullDate)
}
/**
* 设置日期
* @param {Object} date
*/
setDate(date) {
this.selectDate = this.getDate(date)
this._getWeek(this.selectDate.fullDate)
}
/**
* 清理多选状态
*/
cleanMultipleStatus() {
this.multipleStatus = {
before: '',
after: '',
data: []
}
}
/**
* 重置开始日期
*/
resetSatrtDate(startDate) {
// 范围开始
this.startDate = startDate
}
/**
* 重置结束日期
*/
resetEndDate(endDate) {
// 范围结束
this.endDate = endDate
}
/**
* 获取任意时间
*/
getDate(date, AddDayCount = 0, str = 'day') {
if (!date) {
date = new Date()
}
if (typeof date !== 'object') {
date = date.replace(/-/g, '/')
}
const dd = new Date(date)
switch (str) {
case 'day':
dd.setDate(dd.getDate() + AddDayCount) // 获取AddDayCount天后的日期
break
case 'month':
if (dd.getDate() === 31 && AddDayCount>0) {
dd.setDate(dd.getDate() + AddDayCount)
} else {
const preMonth = dd.getMonth()
dd.setMonth(preMonth + AddDayCount) // 获取AddDayCount天后的日期
const nextMonth = dd.getMonth()
// 处理 pre 切换月份目标月份为2月没有当前日(30 31) 切换错误问题
if(AddDayCount<0 && preMonth!==0 && nextMonth-preMonth>AddDayCount){
dd.setMonth(nextMonth+(nextMonth-preMonth+AddDayCount))
}
// 处理 next 切换月份目标月份为2月没有当前日(30 31) 切换错误问题
if(AddDayCount>0 && nextMonth-preMonth>AddDayCount){
dd.setMonth(nextMonth-(nextMonth-preMonth-AddDayCount))
}
}
break
case 'year':
dd.setFullYear(dd.getFullYear() + AddDayCount) // 获取AddDayCount天后的日期
break
}
const y = dd.getFullYear()
const m = dd.getMonth() + 1 < 10 ? '0' + (dd.getMonth() + 1) : dd.getMonth() + 1 // 获取当前月份的日期,不足10补0
const d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate() // 获取当前几号,不足10补0
return {
fullDate: y + '-' + m + '-' + d,
year: y,
month: m,
date: d,
day: dd.getDay()
}
}
/**
* 获取上月剩余天数
*/
_getLastMonthDays(firstDay, full) {
let dateArr = []
for (let i = firstDay; i > 0; i--) {
const beforeDate = new Date(full.year, full.month - 1, -i + 1).getDate()
dateArr.push({
date: beforeDate,
month: full.month - 1,
lunar: this.getlunar(full.year, full.month - 1, beforeDate),
disable: true
})
}
return dateArr
}
/**
* 获取本月天数
*/
_currentMonthDys(dateData, full) {
let dateArr = []
let fullDate = this.date.fullDate
for (let i = 1; i <= dateData; i++) {
let nowDate = full.year + '-' + (full.month < 10 ?
full.month : full.month) + '-' + (i < 10 ?
'0' + i : i)
// 是否今天
let isDay = fullDate === nowDate
// 获取打点信息
let info = this.selected && this.selected.find((item) => {
if (this.dateEqual(nowDate, item.date)) {
return item
}
})
// 日期禁用
let disableBefore = true
let disableAfter = true
if (this.startDate) {
// let dateCompBefore = this.dateCompare(this.startDate, fullDate)
// disableBefore = this.dateCompare(dateCompBefore ? this.startDate : fullDate, nowDate)
disableBefore = this.dateCompare(this.startDate, nowDate)
}
if (this.endDate) {
// let dateCompAfter = this.dateCompare(fullDate, this.endDate)
// disableAfter = this.dateCompare(nowDate, dateCompAfter ? this.endDate : fullDate)
disableAfter = this.dateCompare(nowDate, this.endDate)
}
let multiples = this.multipleStatus.data
let checked = false
let multiplesStatus = -1
if (this.range) {
if (multiples) {
multiplesStatus = multiples.findIndex((item) => {
return this.dateEqual(item, nowDate)
})
}
if (multiplesStatus !== -1) {
checked = true
}
}
let data = {
fullDate: nowDate,
year: full.year,
date: i,
multiple: this.range ? checked : false,
beforeMultiple: this.dateEqual(this.multipleStatus.before, nowDate),
afterMultiple: this.dateEqual(this.multipleStatus.after, nowDate),
month: full.month,
lunar: this.getlunar(full.year, full.month, i),
disable: !(disableBefore && disableAfter),
isDay
}
if (info) {
data.extraInfo = info
}
dateArr.push(data)
}
return dateArr
}
/**
* 获取下月天数
*/
_getNextMonthDays(surplus, full) {
let dateArr = []
for (let i = 1; i < surplus + 1; i++) {
dateArr.push({
date: i,
month: Number(full.month) + 1,
lunar: this.getlunar(full.year, Number(full.month) + 1, i),
disable: true
})
}
return dateArr
}
/**
* 获取当前日期详情
* @param {Object} date
*/
getInfo(date) {
if (!date) {
date = new Date()
}
const dateInfo = this.canlender.find(item => item.fullDate === this.getDate(date).fullDate)
return dateInfo
}
/**
* 比较时间大小
*/
dateCompare(startDate, endDate) {
// 计算截止时间
startDate = new Date(startDate.replace('-', '/').replace('-', '/'))
// 计算详细项的截止时间
endDate = new Date(endDate.replace('-', '/').replace('-', '/'))
if (startDate <= endDate) {
return true
} else {
return false
}
}
/**
* 比较时间是否相等
*/
dateEqual(before, after) {
// 计算截止时间
before = new Date(before.replace('-', '/').replace('-', '/'))
// 计算详细项的截止时间
after = new Date(after.replace('-', '/').replace('-', '/'))
if (before.getTime() - after.getTime() === 0) {
return true
} else {
return false
}
}
/**
* 获取日期范围内所有日期
* @param {Object} begin
* @param {Object} end
*/
geDateAll(begin, end) {
var arr = []
var ab = begin.split('-')
var ae = end.split('-')
var db = new Date()
db.setFullYear(ab[0], ab[1] - 1, ab[2])
var de = new Date()
de.setFullYear(ae[0], ae[1] - 1, ae[2])
var unixDb = db.getTime() - 24 * 60 * 60 * 1000
var unixDe = de.getTime() - 24 * 60 * 60 * 1000
for (var k = unixDb; k <= unixDe;) {
k = k + 24 * 60 * 60 * 1000
arr.push(this.getDate(new Date(parseInt(k))).fullDate)
}
return arr
}
/**
* 计算阴历日期显示
*/
getlunar(year, month, date) {
return CALENDAR.solar2lunar(year, month, date)
}
/**
* 设置打点
*/
setSelectInfo(data, value) {
this.selected = value
this._getWeek(data)
}
/**
* 获取多选状态
*/
setMultiple(fullDate) {
let {
before,
after
} = this.multipleStatus
if (!this.range) return
if (before && after) {
this.multipleStatus.before = ''
this.multipleStatus.after = ''
this.multipleStatus.data = []
} else {
if (!before) {
this.multipleStatus.before = fullDate
} else {
this.multipleStatus.after = fullDate
if (this.dateCompare(this.multipleStatus.before, this.multipleStatus.after)) {
this.multipleStatus.data = this.geDateAll(this.multipleStatus.before, this.multipleStatus.after);
} else {
this.multipleStatus.data = this.geDateAll(this.multipleStatus.after, this.multipleStatus.before);
}
}
}
this._getWeek(fullDate)
}
/**
* 获取每周数据
* @param {Object} dateData
*/
_getWeek(dateData) {
const {
year,
month
} = this.getDate(dateData)
let firstDay = new Date(year, month - 1, 1).getDay()
let currentDay = new Date(year, month, 0).getDate()
let dates = {
lastMonthDays: this._getLastMonthDays(firstDay, this.getDate(dateData)), // 上个月末尾几天
currentMonthDys: this._currentMonthDys(currentDay, this.getDate(dateData)), // 本月天数
nextMonthDays: [], // 下个月开始几天
weeks: []
}
let canlender = []
const surplus = 42 - (dates.lastMonthDays.length + dates.currentMonthDys.length)
dates.nextMonthDays = this._getNextMonthDays(surplus, this.getDate(dateData))
canlender = canlender.concat(dates.lastMonthDays, dates.currentMonthDys, dates.nextMonthDays)
let weeks = {}
// 拼接数组 上个月开始几天 + 本月天数+ 下个月开始几天
for (let i = 0; i < canlender.length; i++) {
if (i % 7 === 0) {
weeks[parseInt(i / 7)] = new Array(7)
}
weeks[parseInt(i / 7)][i % 7] = canlender[i]
}
this.canlender = canlender
this.weeks = weeks
}
//静态方法
// static init(date) {
// if (!this.instance) {
// this.instance = new Calendar(date);
// }
// return this.instance;
// }
}
export default Calendar
@@ -0,0 +1,85 @@
{
"id": "uni-calendar",
"displayName": "uni-calendar 日历",
"version": "1.4.11",
"description": "日历组件",
"keywords": [
"uni-ui",
"uniui",
"日历",
"",
"打卡",
"日历选择"
],
"repository": "https://github.com/dcloudio/uni-ui",
"engines": {
"HBuilderX": ""
},
"directories": {
"example": "../../temps/example_temps"
},
"dcloudext": {
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "https://www.npmjs.com/package/@dcloudio/uni-ui",
"type": "component-vue"
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y"
},
"client": {
"App": {
"app-vue": "y",
"app-nvue": "y"
},
"H5-mobile": {
"Safari": "y",
"Android Browser": "y",
"微信浏览器(Android)": "y",
"QQ浏览器(Android)": "y"
},
"H5-pc": {
"Chrome": "y",
"IE": "y",
"Edge": "y",
"Firefox": "y",
"Safari": "y"
},
"小程序": {
"微信": "y",
"阿里": "y",
"百度": "y",
"字节跳动": "y",
"QQ": "y"
},
"快应用": {
"华为": "u",
"联盟": "u"
},
"Vue": {
"vue2": "y",
"vue3": "y"
}
}
}
}
}
+103
View File
@@ -0,0 +1,103 @@
## Calendar 日历
> **组件名:uni-calendar**
> 代码块: `uCalendar`
日历组件
> **注意事项**
> 为了避免错误使用,给大家带来不好的开发体验,请在使用组件前仔细阅读下面的注意事项,可以帮你避免一些错误。
> - 本组件农历转换使用的js是 [@1900-2100区间内的公历、农历互转](https://github.com/jjonline/calendar.js)
> - 仅支持自定义组件模式
> - `date`属性传入的应该是一个 String ,如: 2019-06-27 ,而不是 new Date()
> - 通过 `insert` 属性来确定当前的事件是 @change 还是 @confirm 。理应合并为一个事件,但是为了区分模式,现使用两个事件,这里需要注意
> - 弹窗模式下无法阻止后面的元素滚动,如有需要阻止,请在弹窗弹出后,手动设置滚动元素为不可滚动
### 安装方式
本组件符合[easycom](https://uniapp.dcloud.io/collocation/pages?id=easycom)规范,`HBuilderX 2.5.5`起,只需将本组件导入项目,在页面`template`中即可直接使用,无需在页面中`import`和注册`components`。
如需通过`npm`方式使用`uni-ui`组件,另见文档:[https://ext.dcloud.net.cn/plugin?id=55](https://ext.dcloud.net.cn/plugin?id=55)
### 基本用法
在 ``template`` 中使用组件
```html
<view>
<uni-calendar
:insert="true"
:lunar="true"
:start-date="'2019-3-2'"
:end-date="'2019-5-20'"
@change="change"
/>
</view>
```
### 通过方法打开日历
需要设置 `insert` 为 `false`
```html
<view>
<uni-calendar
ref="calendar"
:insert="false"
@confirm="confirm"
/>
<button @click="open">打开日历</button>
</view>
```
```javascript
export default {
data() {
return {};
},
methods: {
open(){
this.$refs.calendar.open();
},
confirm(e) {
console.log(e);
}
}
};
```
## API
### Calendar Props
| 属性名 | 类型 | 默认值| 说明 |
| - | - | - | - |
| date | String |- | 自定义当前时间,默认为今天 |
| lunar | Boolean | false | 显示农历 |
| startDate | String |- | 日期选择范围-开始日期 |
| endDate | String |- | 日期选择范围-结束日期 |
| range | Boolean | false | 范围选择 |
| insert | Boolean | false | 插入模式,可选值,ture:插入模式;false:弹窗模式;默认为插入模式 |
|clearDate |Boolean |true |弹窗模式是否清空上次选择内容 |
| selected | Array |- | 打点,期待格式[{date: '2019-06-27', info: '签到', data: { custom: '自定义信息', name: '自定义消息头',xxx:xxx... }}] |
|showMonth | Boolean | true | 是否显示月份为背景 |
### Calendar Events
| 事件名 | 说明 |返回值|
| - | - | - |
| open | 弹出日历组件,`insert :false` 时生效|- |
## 组件示例
点击查看:[https://hellouniapp.dcloud.net.cn/pages/extUI/calendar/calendar](https://hellouniapp.dcloud.net.cn/pages/extUI/calendar/calendar)
+26
View File
@@ -0,0 +1,26 @@
## 1.3.1(2021-12-20)
- 修复 在vue页面下略缩图显示不正常的bug
## 1.3.0(2021-11-19)
- 重构插槽的用法 ,header 替换为 title
- 新增 actions 插槽
- 新增 cover 封面图属性和插槽
- 新增 padding 内容默认内边距离
- 新增 margin 卡片默认外边距离
- 新增 spacing 卡片默认内边距
- 新增 shadow 卡片阴影属性
- 取消 mode 属性,可使用组合插槽代替
- 取消 note 属性 ,使用actions插槽代替
- 优化 组件UI,并提供设计资源,详见:[https://uniapp.dcloud.io/component/uniui/resource](https://uniapp.dcloud.io/component/uniui/resource)
- 文档迁移,详见:[https://uniapp.dcloud.io/component/uniui/uni-card](https://uniapp.dcloud.io/component/uniui/uni-card)
## 1.2.1(2021-07-30)
- 优化 vue3下事件警告的问题
## 1.2.0(2021-07-13)
- 组件兼容 vue3,如何创建vue3项目详见 [uni-app 项目支持 vue3 介绍](https://ask.dcloud.net.cn/article/37834)
## 1.1.8(2021-07-01)
- 优化 图文卡片无图片加载时,提供占位图标
- 新增 header 插槽,自定义卡片头部( 图文卡片 mode="style" 时,不支持)
- 修复 thumbnail 不存在仍然占位的 bug
## 1.1.7(2021-05-12)
- 新增 组件示例地址
## 1.1.6(2021-02-04)
- 调整为uni_modules目录规范
@@ -0,0 +1,270 @@
<template>
<view class="uni-card" :class="{ 'uni-card--full': isFull, 'uni-card--shadow': isShadow,'uni-card--border':border}"
:style="{'margin':isFull?0:margin,'padding':spacing,'box-shadow':isShadow?shadow:''}">
<!-- 封面 -->
<slot name="cover">
<view v-if="cover" class="uni-card__cover">
<image class="uni-card__cover-image" mode="widthFix" @click="onClick('cover')" :src="cover"></image>
</view>
</slot>
<slot name="title">
<view v-if="title || extra" class="uni-card__header">
<!-- 卡片标题 -->
<view class="uni-card__header-box" @click="onClick('title')">
<view v-if="thumbnail" class="uni-card__header-avatar">
<image class="uni-card__header-avatar-image" :src="thumbnail" mode="aspectFit" />
</view>
<view class="uni-card__header-content">
<text class="uni-card__header-content-title uni-ellipsis">{{ title }}</text>
<text v-if="title&&subTitle"
class="uni-card__header-content-subtitle uni-ellipsis">{{ subTitle }}</text>
</view>
</view>
<view class="uni-card__header-extra" @click="onClick('extra')">
<text class="uni-card__header-extra-text">{{ extra }}</text>
</view>
</view>
</slot>
<!-- 卡片内容 -->
<view class="uni-card__content" :style="{padding:padding}" @click="onClick('content')">
<slot></slot>
</view>
<view class="uni-card__actions" @click="onClick('actions')">
<slot name="actions"></slot>
</view>
</view>
</template>
<script>
/**
* Card 卡片
* @description 卡片视图组件
* @tutorial https://ext.dcloud.net.cn/plugin?id=22
* @property {String} title 标题文字
* @property {String} subTitle 副标题
* @property {Number} padding 内容内边距
* @property {Number} margin 卡片外边距
* @property {Number} spacing 卡片内边距
* @property {String} extra 标题额外信息
* @property {String} cover 封面图(本地路径需要引入)
* @property {String} thumbnail 标题左侧缩略图
* @property {Boolean} is-full = [true | false] 卡片内容是否通栏,为 true 时将去除padding值
* @property {Boolean} is-shadow = [true | false] 卡片内容是否开启阴影
* @property {String} shadow 卡片阴影
* @property {Boolean} border 卡片边框
* @event {Function} click 点击 Card 触发事件
*/
export default {
name: 'UniCard',
emits: ['click'],
props: {
title: {
type: String,
default: ''
},
subTitle: {
type: String,
default: ''
},
padding: {
type: String,
default: '10px'
},
margin: {
type: String,
default: '15px'
},
spacing: {
type: String,
default: '0 10px'
},
extra: {
type: String,
default: ''
},
cover: {
type: String,
default: ''
},
thumbnail: {
type: String,
default: ''
},
isFull: {
// 内容区域是否通栏
type: Boolean,
default: false
},
isShadow: {
// 是否开启阴影
type: Boolean,
default: true
},
shadow: {
type: String,
default: '0px 0px 3px 1px rgba(0, 0, 0, 0.08)'
},
border: {
type: Boolean,
default: true
}
},
methods: {
onClick(type) {
this.$emit('click', type)
}
}
}
</script>
<style lang="scss">
$uni-border-3: #EBEEF5 !default;
$uni-shadow-base:0 0px 6px 1px rgba($color: #a5a5a5, $alpha: 0.2) !default;
$uni-main-color: #3a3a3a !default;
$uni-base-color: #6a6a6a !default;
$uni-secondary-color: #909399 !default;
$uni-spacing-sm: 8px !default;
$uni-border-color:$uni-border-3;
$uni-shadow: $uni-shadow-base;
$uni-card-title: 15px;
$uni-cart-title-color:$uni-main-color;
$uni-card-subtitle: 12px;
$uni-cart-subtitle-color:$uni-secondary-color;
$uni-card-spacing: 10px;
$uni-card-content-color: $uni-base-color;
.uni-card {
margin: $uni-card-spacing;
padding: 0 $uni-spacing-sm;
border-radius: 4px;
overflow: hidden;
font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, SimSun, sans-serif;
background-color: #fff;
flex: 1;
.uni-card__cover {
position: relative;
margin-top: $uni-card-spacing;
flex-direction: row;
overflow: hidden;
border-radius: 4px;
.uni-card__cover-image {
flex: 1;
// width: 100%;
/* #ifndef APP-PLUS */
vertical-align: middle;
/* #endif */
}
}
.uni-card__header {
display: flex;
border-bottom: 1px $uni-border-color solid;
flex-direction: row;
align-items: center;
padding: $uni-card-spacing;
overflow: hidden;
.uni-card__header-box {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex: 1;
flex-direction: row;
align-items: center;
overflow: hidden;
}
.uni-card__header-avatar {
width: 40px;
height: 40px;
overflow: hidden;
border-radius: 5px;
margin-right: $uni-card-spacing;
.uni-card__header-avatar-image {
flex: 1;
width: 40px;
height: 40px;
}
}
.uni-card__header-content {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
justify-content: center;
flex: 1;
// height: 40px;
overflow: hidden;
.uni-card__header-content-title {
font-size: $uni-card-title;
color: $uni-cart-title-color;
// line-height: 22px;
}
.uni-card__header-content-subtitle {
font-size: $uni-card-subtitle;
margin-top: 5px;
color: $uni-cart-subtitle-color;
}
}
.uni-card__header-extra {
line-height: 12px;
.uni-card__header-extra-text {
font-size: 12px;
color: $uni-cart-subtitle-color;
}
}
}
.uni-card__content {
padding: $uni-card-spacing;
font-size: 14px;
color: $uni-card-content-color;
line-height: 22px;
}
.uni-card__actions {
font-size: 12px;
}
}
.uni-card--border {
border: 1px solid $uni-border-color;
}
.uni-card--shadow {
position: relative;
/* #ifndef APP-NVUE */
box-shadow: $uni-shadow;
/* #endif */
}
.uni-card--full {
margin: 0;
border-left-width: 0;
border-left-width: 0;
border-radius: 0;
}
/* #ifndef APP-NVUE */
.uni-card--full:after {
border-radius: 0;
}
/* #endif */
.uni-ellipsis {
/* #ifndef APP-NVUE */
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
/* #endif */
/* #ifdef APP-NVUE */
lines: 1;
/* #endif */
}
</style>
+90
View File
@@ -0,0 +1,90 @@
{
"id": "uni-card",
"displayName": "uni-card 卡片",
"version": "1.3.1",
"description": "Card 组件,提供常见的卡片样式。",
"keywords": [
"uni-ui",
"uniui",
"card",
"",
"卡片"
],
"repository": "https://github.com/dcloudio/uni-ui",
"engines": {
"HBuilderX": ""
},
"directories": {
"example": "../../temps/example_temps"
},
"dcloudext": {
"category": [
"前端组件",
"通用组件"
],
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "https://www.npmjs.com/package/@dcloudio/uni-ui"
},
"uni_modules": {
"dependencies": [
"uni-icons",
"uni-scss"
],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y"
},
"client": {
"App": {
"app-vue": "y",
"app-nvue": "y"
},
"H5-mobile": {
"Safari": "y",
"Android Browser": "y",
"微信浏览器(Android)": "y",
"QQ浏览器(Android)": "y"
},
"H5-pc": {
"Chrome": "y",
"IE": "y",
"Edge": "y",
"Firefox": "y",
"Safari": "y"
},
"小程序": {
"微信": "y",
"阿里": "y",
"百度": "y",
"字节跳动": "y",
"QQ": "y"
},
"快应用": {
"华为": "u",
"联盟": "u"
},
"Vue": {
"vue2": "y",
"vue3": "y"
}
}
}
}
}
+12
View File
@@ -0,0 +1,12 @@
## Card 卡片
> **组件名:uni-card**
> 代码块: `uCard`
卡片视图组件。
### [查看文档](https://uniapp.dcloud.io/component/uniui/uni-card)
#### 如使用过程中有任何问题,或者您对uni-ui有一些好的建议,欢迎加入 uni-ui 交流群:871950839
@@ -0,0 +1,38 @@
## 1.4.4(2024-03-20)
- 修复 titleBorder类型修正
## 1.4.3(2022-01-25)
- 修复 初始化的时候 ,open 属性失效的bug
## 1.4.2(2022-01-21)
- 修复 微信小程序resize后组件收起的bug
## 1.4.1(2021-11-22)
- 修复 vue3中个别scss变量无法找到的问题
## 1.4.0(2021-11-19)
- 优化 组件UI,并提供设计资源,详见:[https://uniapp.dcloud.io/component/uniui/resource](https://uniapp.dcloud.io/component/uniui/resource)
- 文档迁移,详见:[https://uniapp.dcloud.io/component/uniui/uni-collapse](https://uniapp.dcloud.io/component/uniui/uni-collapse)
## 1.3.3(2021-08-17)
- 优化 show-arrow 属性默认为true
## 1.3.2(2021-08-17)
- 新增 show-arrow 属性,控制是否显示右侧箭头
## 1.3.1(2021-07-30)
- 优化 vue3下小程序事件警告的问题
## 1.3.0(2021-07-30)
- 组件兼容 vue3,如何创建vue3项目,详见 [uni-app 项目支持 vue3 介绍](https://ask.dcloud.net.cn/article/37834)
## 1.2.2(2021-07-21)
- 修复 由1.2.0版本引起的 change 事件返回 undefined 的Bug
## 1.2.1(2021-07-21)
- 优化 组件示例
## 1.2.0(2021-07-21)
- 新增 组件折叠动画
- 新增 value\v-model 属性 ,动态修改面板折叠状态
- 新增 title 插槽 ,可定义面板标题
- 新增 border 属性 ,显示隐藏面板内容分隔线
- 新增 title-border 属性 ,显示隐藏面板标题分隔线
- 修复 resize 方法失效的Bug
- 修复 change 事件返回参数不正确的Bug
- 优化 H5、App 平台自动更具内容更新高度,无需调用 reszie() 方法
## 1.1.7(2021-05-12)
- 新增 组件示例地址
## 1.1.6(2021-02-05)
- 优化 组件引用关系,通过uni_modules引用组件
## 1.1.5(2021-02-05)
- 调整为uni_modules目录规范
@@ -0,0 +1,402 @@
<template>
<view class="uni-collapse-item">
<!-- onClick(!isOpen) -->
<view @click="onClick(!isOpen)" class="uni-collapse-item__title"
:class="{'is-open':isOpen &&titleBorder === 'auto' ,'uni-collapse-item-border':titleBorder !== 'none'}">
<view class="uni-collapse-item__title-wrap">
<slot name="title">
<view class="uni-collapse-item__title-box" :class="{'is-disabled':disabled}">
<image v-if="thumb" :src="thumb" class="uni-collapse-item__title-img" />
<text class="uni-collapse-item__title-text">{{ title }}</text>
</view>
</slot>
</view>
<view v-if="showArrow"
:class="{ 'uni-collapse-item__title-arrow-active': isOpen, 'uni-collapse-item--animation': showAnimation === true }"
class="uni-collapse-item__title-arrow">
<uni-icons :color="disabled?'#ddd':'#bbb'" size="14" type="bottom" />
</view>
</view>
<view class="uni-collapse-item__wrap" :class="{'is--transition':showAnimation}"
:style="{height: (isOpen?height:0) +'px'}">
<view :id="elId" ref="collapse--hook" class="uni-collapse-item__wrap-content"
:class="{open:isheight,'uni-collapse-item--border':border&&isOpen}">
<slot></slot>
</view>
</view>
</view>
</template>
<script>
// #ifdef APP-NVUE
const dom = weex.requireModule('dom')
// #endif
/**
* CollapseItem 折叠面板子组件
* @description 折叠面板子组件
* @property {String} title 标题文字
* @property {String} thumb 标题左侧缩略图
* @property {String} name 唯一标志符
* @property {Boolean} open = [true|false] 是否展开组件
* @property {Boolean} titleBorder = [true|false] 是否显示标题分隔线
* @property {String} border = ['auto'|'show'|'none'] 是否显示分隔线
* @property {Boolean} disabled = [true|false] 是否展开面板
* @property {Boolean} showAnimation = [true|false] 开启动画
* @property {Boolean} showArrow = [true|false] 是否显示右侧箭头
*/
export default {
name: 'uniCollapseItem',
props: {
// 列表标题
title: {
type: String,
default: ''
},
name: {
type: [Number, String],
default: ''
},
// 是否禁用
disabled: {
type: Boolean,
default: false
},
// #ifdef APP-PLUS
// 是否显示动画,app 端默认不开启动画,卡顿严重
showAnimation: {
type: Boolean,
default: false
},
// #endif
// #ifndef APP-PLUS
// 是否显示动画
showAnimation: {
type: Boolean,
default: true
},
// #endif
// 是否展开
open: {
type: Boolean,
default: false
},
// 缩略图
thumb: {
type: String,
default: ''
},
// 标题分隔线显示类型
titleBorder: {
type: String,
default: 'auto'
},
border: {
type: Boolean,
default: true
},
showArrow: {
type: Boolean,
default: true
}
},
data() {
// TODO 随机生生元素ID,解决百度小程序获取同一个元素位置信息的bug
const elId = `Uni_${Math.ceil(Math.random() * 10e5).toString(36)}`
return {
isOpen: false,
isheight: null,
height: 0,
elId,
nameSync: 0
}
},
watch: {
open(val) {
this.isOpen = val
this.onClick(val, 'init')
}
},
updated(e) {
this.$nextTick(() => {
this.init(true)
})
},
created() {
this.collapse = this.getCollapse()
this.oldHeight = 0
this.onClick(this.open, 'init')
},
// #ifndef VUE3
// TODO vue2
destroyed() {
if (this.__isUnmounted) return
this.uninstall()
},
// #endif
// #ifdef VUE3
// TODO vue3
unmounted() {
this.__isUnmounted = true
this.uninstall()
},
// #endif
mounted() {
if (!this.collapse) return
if (this.name !== '') {
this.nameSync = this.name
} else {
this.nameSync = this.collapse.childrens.length + ''
}
if (this.collapse.names.indexOf(this.nameSync) === -1) {
this.collapse.names.push(this.nameSync)
} else {
console.warn(`name 值 ${this.nameSync} 重复`);
}
if (this.collapse.childrens.indexOf(this) === -1) {
this.collapse.childrens.push(this)
}
this.init()
},
methods: {
init(type) {
// #ifndef APP-NVUE
this.getCollapseHeight(type)
// #endif
// #ifdef APP-NVUE
this.getNvueHwight(type)
// #endif
},
uninstall() {
if (this.collapse) {
this.collapse.childrens.forEach((item, index) => {
if (item === this) {
this.collapse.childrens.splice(index, 1)
}
})
this.collapse.names.forEach((item, index) => {
if (item === this.nameSync) {
this.collapse.names.splice(index, 1)
}
})
}
},
onClick(isOpen, type) {
if (this.disabled) return
this.isOpen = isOpen
if (this.isOpen && this.collapse) {
this.collapse.setAccordion(this)
}
if (type !== 'init') {
this.collapse.onChange(isOpen, this)
}
},
getCollapseHeight(type, index = 0) {
const views = uni.createSelectorQuery().in(this)
views
.select(`#${this.elId}`)
.fields({
size: true
}, data => {
// TODO 百度中可能获取不到节点信息 ,需要循环获取
if (index >= 10) return
if (!data) {
index++
this.getCollapseHeight(false, index)
return
}
// #ifdef APP-NVUE
this.height = data.height + 1
// #endif
// #ifndef APP-NVUE
this.height = data.height
// #endif
this.isheight = true
if (type) return
this.onClick(this.isOpen, 'init')
})
.exec()
},
getNvueHwight(type) {
const result = dom.getComponentRect(this.$refs['collapse--hook'], option => {
if (option && option.result && option.size) {
// #ifdef APP-NVUE
this.height = option.size.height + 1
// #endif
// #ifndef APP-NVUE
this.height = option.size.height
// #endif
this.isheight = true
if (type) return
this.onClick(this.open, 'init')
}
})
},
/**
* 获取父元素实例
*/
getCollapse(name = 'uniCollapse') {
let parent = this.$parent;
let parentName = parent.$options.name;
while (parentName !== name) {
parent = parent.$parent;
if (!parent) return false;
parentName = parent.$options.name;
}
return parent;
}
}
}
</script>
<style lang="scss">
.uni-collapse-item {
/* #ifndef APP-NVUE */
box-sizing: border-box;
/* #endif */
&__title {
/* #ifndef APP-NVUE */
display: flex;
width: 100%;
box-sizing: border-box;
/* #endif */
flex-direction: row;
align-items: center;
transition: border-bottom-color .3s;
// transition-property: border-bottom-color;
// transition-duration: 5s;
&-wrap {
width: 100%;
flex: 1;
}
&-box {
padding: 0 15px;
/* #ifndef APP-NVUE */
display: flex;
width: 100%;
box-sizing: border-box;
/* #endif */
flex-direction: row;
justify-content: space-between;
align-items: center;
height: 48px;
line-height: 48px;
background-color: #fff;
color: #303133;
font-size: 13px;
font-weight: 500;
/* #ifdef H5 */
cursor: pointer;
outline: none;
/* #endif */
&.is-disabled {
.uni-collapse-item__title-text {
color: #999;
}
}
}
&.uni-collapse-item-border {
border-bottom: 1px solid #ebeef5;
}
&.is-open {
border-bottom-color: transparent;
}
&-img {
height: 22px;
width: 22px;
margin-right: 10px;
}
&-text {
flex: 1;
font-size: 14px;
/* #ifndef APP-NVUE */
white-space: nowrap;
color: inherit;
/* #endif */
/* #ifdef APP-NVUE */
lines: 1;
/* #endif */
overflow: hidden;
text-overflow: ellipsis;
}
&-arrow {
/* #ifndef APP-NVUE */
display: flex;
box-sizing: border-box;
/* #endif */
align-items: center;
justify-content: center;
width: 20px;
height: 20px;
margin-right: 10px;
transform: rotate(0deg);
&-active {
transform: rotate(-180deg);
}
}
}
&__wrap {
/* #ifndef APP-NVUE */
will-change: height;
box-sizing: border-box;
/* #endif */
background-color: #fff;
overflow: hidden;
position: relative;
height: 0;
&.is--transition {
// transition: all 0.3s;
transition-property: height, border-bottom-width;
transition-duration: 0.3s;
/* #ifndef APP-NVUE */
will-change: height;
/* #endif */
}
&-content {
position: absolute;
font-size: 13px;
color: #303133;
// transition: height 0.3s;
border-bottom-color: transparent;
border-bottom-style: solid;
border-bottom-width: 0;
&.uni-collapse-item--border {
border-bottom-width: 1px;
border-bottom-color: red;
border-bottom-color: #ebeef5;
}
&.open {
position: relative;
}
}
}
&--animation {
transition-property: transform;
transition-duration: 0.3s;
transition-timing-function: ease;
}
}
</style>
@@ -0,0 +1,147 @@
<template>
<view class="uni-collapse">
<slot />
</view>
</template>
<script>
/**
* Collapse 折叠面板
* @description 展示可以折叠 / 展开的内容区域
* @tutorial https://ext.dcloud.net.cn/plugin?id=23
* @property {String|Array} value 当前激活面板改变时触发(如果是手风琴模式,参数类型为string,否则为array)
* @property {Boolean} accordion = [true|false] 是否开启手风琴效果是否开启手风琴效果
* @event {Function} change 切换面板时触发,如果是手风琴模式,返回类型为string,否则为array
*/
export default {
name: 'uniCollapse',
emits:['change','activeItem','input','update:modelValue'],
props: {
value: {
type: [String, Array],
default: ''
},
modelValue: {
type: [String, Array],
default: ''
},
accordion: {
// 是否开启手风琴效果
type: [Boolean, String],
default: false
},
},
data() {
return {}
},
computed: {
// TODO 兼容 vue2 和 vue3
dataValue() {
let value = (typeof this.value === 'string' && this.value === '') ||
(Array.isArray(this.value) && this.value.length === 0)
let modelValue = (typeof this.modelValue === 'string' && this.modelValue === '') ||
(Array.isArray(this.modelValue) && this.modelValue.length === 0)
if (value) {
return this.modelValue
}
if (modelValue) {
return this.value
}
return this.value
}
},
watch: {
dataValue(val) {
this.setOpen(val)
}
},
created() {
this.childrens = []
this.names = []
},
mounted() {
this.$nextTick(()=>{
this.setOpen(this.dataValue)
})
},
methods: {
setOpen(val) {
let str = typeof val === 'string'
let arr = Array.isArray(val)
this.childrens.forEach((vm, index) => {
if (str) {
if (val === vm.nameSync) {
if (!this.accordion) {
console.warn('accordion 属性为 false ,v-model 类型应该为 array')
return
}
vm.isOpen = true
}
}
if (arr) {
val.forEach(v => {
if (v === vm.nameSync) {
if (this.accordion) {
console.warn('accordion 属性为 true ,v-model 类型应该为 string')
return
}
vm.isOpen = true
}
})
}
})
this.emit(val)
},
setAccordion(self) {
if (!this.accordion) return
this.childrens.forEach((vm, index) => {
if (self !== vm) {
vm.isOpen = false
}
})
},
resize() {
this.childrens.forEach((vm, index) => {
// #ifndef APP-NVUE
vm.getCollapseHeight()
// #endif
// #ifdef APP-NVUE
vm.getNvueHwight()
// #endif
})
},
onChange(isOpen, self) {
let activeItem = []
if (this.accordion) {
activeItem = isOpen ? self.nameSync : ''
} else {
this.childrens.forEach((vm, index) => {
if (vm.isOpen) {
activeItem.push(vm.nameSync)
}
})
}
this.$emit('change', activeItem)
this.emit(activeItem)
},
emit(val){
this.$emit('input', val)
this.$emit('update:modelValue', val)
}
}
}
</script>
<style lang="scss" >
.uni-collapse {
/* #ifndef APP-NVUE */
width: 100%;
display: flex;
/* #endif */
/* #ifdef APP-NVUE */
flex: 1;
/* #endif */
flex-direction: column;
background-color: #fff;
}
</style>
@@ -0,0 +1,86 @@
{
"id": "uni-collapse",
"displayName": "uni-collapse 折叠面板",
"version": "1.4.4",
"description": "Collapse 组件,可以折叠 / 展开的内容区域。",
"keywords": [
"uni-ui",
"折叠",
"折叠面板",
"手风琴"
],
"repository": "https://github.com/dcloudio/uni-ui",
"engines": {
"HBuilderX": ""
},
"directories": {
"example": "../../temps/example_temps"
},
"dcloudext": {
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "https://www.npmjs.com/package/@dcloudio/uni-ui",
"type": "component-vue"
},
"uni_modules": {
"dependencies": [
"uni-scss",
"uni-icons"
],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y"
},
"client": {
"App": {
"app-vue": "y",
"app-nvue": "y"
},
"H5-mobile": {
"Safari": "y",
"Android Browser": "y",
"微信浏览器(Android)": "y",
"QQ浏览器(Android)": "y"
},
"H5-pc": {
"Chrome": "y",
"IE": "y",
"Edge": "y",
"Firefox": "y",
"Safari": "y"
},
"小程序": {
"微信": "y",
"阿里": "y",
"百度": "y",
"字节跳动": "y",
"QQ": "y"
},
"快应用": {
"华为": "u",
"联盟": "u"
},
"Vue": {
"vue2": "y",
"vue3": "y"
}
}
}
}
}
+12
View File
@@ -0,0 +1,12 @@
## Collapse 折叠面板
> **组件名:uni-collapse**
> 代码块: `uCollapse`
> 关联组件:`uni-collapse-item`、`uni-icons`。
折叠面板用来折叠/显示过长的内容或者是列表。通常是在多内容分类项使用,折叠不重要的内容,显示重要内容。点击可以展开折叠部分。
### [查看文档](https://uniapp.dcloud.io/component/uniui/uni-collapse)
#### 如使用过程中有任何问题,或者您对uni-ui有一些好的建议,欢迎加入 uni-ui 交流群:871950839
@@ -0,0 +1,15 @@
## 1.0.1(2021-11-23)
- 优化 label、label-width 属性
## 1.0.0(2021-11-19)
- 优化 组件UI,并提供设计资源,详见:[https://uniapp.dcloud.io/component/uniui/resource](https://uniapp.dcloud.io/component/uniui/resource)
- 文档迁移,详见:[https://uniapp.dcloud.io/component/uniui/uni-combox](https://uniapp.dcloud.io/component/uniui/uni-combox)
## 0.1.0(2021-07-30)
- 组件兼容 vue3,如何创建vue3项目,详见 [uni-app 项目支持 vue3 介绍](https://ask.dcloud.net.cn/article/37834)
## 0.0.6(2021-05-12)
- 新增 组件示例地址
## 0.0.5(2021-04-21)
- 优化 添加依赖 uni-icons, 导入后自动下载依赖
## 0.0.4(2021-02-05)
- 优化 组件引用关系,通过uni_modules引用组件
## 0.0.3(2021-02-04)
- 调整为uni_modules目录规范
@@ -0,0 +1,275 @@
<template>
<view class="uni-combox" :class="border ? '' : 'uni-combox__no-border'">
<view v-if="label" class="uni-combox__label" :style="labelStyle">
<text>{{label}}</text>
</view>
<view class="uni-combox__input-box">
<input class="uni-combox__input" type="text" :placeholder="placeholder"
placeholder-class="uni-combox__input-plac" v-model="inputVal" @input="onInput" @focus="onFocus"
@blur="onBlur" />
<uni-icons :type="showSelector? 'top' : 'bottom'" size="14" color="#999" @click="toggleSelector">
</uni-icons>
</view>
<view class="uni-combox__selector" v-if="showSelector">
<view class="uni-popper__arrow"></view>
<scroll-view scroll-y="true" class="uni-combox__selector-scroll">
<view class="uni-combox__selector-empty" v-if="filterCandidatesLength === 0">
<text>{{emptyTips}}</text>
</view>
<view class="uni-combox__selector-item" v-for="(item,index) in filterCandidates" :key="index"
@click="onSelectorClick(index)">
<text>{{item}}</text>
</view>
</scroll-view>
</view>
</view>
</template>
<script>
/**
* Combox 组合输入框
* @description 组合输入框一般用于既可以输入也可以选择的场景
* @tutorial https://ext.dcloud.net.cn/plugin?id=1261
* @property {String} label 左侧文字
* @property {String} labelWidth 左侧内容宽度
* @property {String} placeholder 输入框占位符
* @property {Array} candidates 候选项列表
* @property {String} emptyTips 筛选结果为空时显示的文字
* @property {String} value 组合框的值
*/
export default {
name: 'uniCombox',
emits: ['input', 'update:modelValue'],
props: {
border: {
type: Boolean,
default: true
},
label: {
type: String,
default: ''
},
labelWidth: {
type: String,
default: 'auto'
},
placeholder: {
type: String,
default: ''
},
candidates: {
type: Array,
default () {
return []
}
},
emptyTips: {
type: String,
default: '无匹配项'
},
// #ifndef VUE3
value: {
type: [String, Number],
default: ''
},
// #endif
// #ifdef VUE3
modelValue: {
type: [String, Number],
default: ''
},
// #endif
},
data() {
return {
showSelector: false,
inputVal: ''
}
},
computed: {
labelStyle() {
if (this.labelWidth === 'auto') {
return ""
}
return `width: ${this.labelWidth}`
},
filterCandidates() {
return this.candidates.filter((item) => {
return item.toString().indexOf(this.inputVal) > -1
})
},
filterCandidatesLength() {
return this.filterCandidates.length
}
},
watch: {
// #ifndef VUE3
value: {
handler(newVal) {
this.inputVal = newVal
},
immediate: true
},
// #endif
// #ifdef VUE3
modelValue: {
handler(newVal) {
this.inputVal = newVal
},
immediate: true
},
// #endif
},
methods: {
toggleSelector() {
this.showSelector = !this.showSelector
},
onFocus() {
this.showSelector = true
},
onBlur() {
setTimeout(() => {
this.showSelector = false
}, 153)
},
onSelectorClick(index) {
this.inputVal = this.filterCandidates[index]
this.showSelector = false
this.$emit('input', this.inputVal)
this.$emit('update:modelValue', this.inputVal)
},
onInput() {
setTimeout(() => {
this.$emit('input', this.inputVal)
this.$emit('update:modelValue', this.inputVal)
})
}
}
}
</script>
<style lang="scss" scoped>
.uni-combox {
font-size: 14px;
border: 1px solid #DCDFE6;
border-radius: 4px;
padding: 6px 10px;
position: relative;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
// height: 40px;
flex-direction: row;
align-items: center;
// border-bottom: solid 1px #DDDDDD;
}
.uni-combox__label {
font-size: 16px;
line-height: 22px;
padding-right: 10px;
color: #999999;
}
.uni-combox__input-box {
position: relative;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex: 1;
flex-direction: row;
align-items: center;
}
.uni-combox__input {
flex: 1;
font-size: 14px;
height: 22px;
line-height: 22px;
}
.uni-combox__input-plac {
font-size: 14px;
color: #999;
}
.uni-combox__selector {
/* #ifndef APP-NVUE */
box-sizing: border-box;
/* #endif */
position: absolute;
top: calc(100% + 12px);
left: 0;
width: 100%;
background-color: #FFFFFF;
border: 1px solid #EBEEF5;
border-radius: 6px;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
z-index: 2;
padding: 4px 0;
}
.uni-combox__selector-scroll {
/* #ifndef APP-NVUE */
max-height: 200px;
box-sizing: border-box;
/* #endif */
}
.uni-combox__selector-empty,
.uni-combox__selector-item {
/* #ifndef APP-NVUE */
display: flex;
cursor: pointer;
/* #endif */
line-height: 36px;
font-size: 14px;
text-align: center;
// border-bottom: solid 1px #DDDDDD;
padding: 0px 10px;
}
.uni-combox__selector-item:hover {
background-color: #f9f9f9;
}
.uni-combox__selector-empty:last-child,
.uni-combox__selector-item:last-child {
/* #ifndef APP-NVUE */
border-bottom: none;
/* #endif */
}
// picker 弹出层通用的指示小三角
.uni-popper__arrow,
.uni-popper__arrow::after {
position: absolute;
display: block;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 6px;
}
.uni-popper__arrow {
filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
top: -6px;
left: 10%;
margin-right: 3px;
border-top-width: 0;
border-bottom-color: #EBEEF5;
}
.uni-popper__arrow::after {
content: " ";
top: 1px;
margin-left: -6px;
border-top-width: 0;
border-bottom-color: #fff;
}
.uni-combox__no-border {
border: none;
}
</style>
@@ -0,0 +1,90 @@
{
"id": "uni-combox",
"displayName": "uni-combox 组合框",
"version": "1.0.1",
"description": "可以选择也可以输入的表单项 ",
"keywords": [
"uni-ui",
"uniui",
"combox",
"组合框",
"select"
],
"repository": "https://github.com/dcloudio/uni-ui",
"engines": {
"HBuilderX": ""
},
"directories": {
"example": "../../temps/example_temps"
},
"dcloudext": {
"category": [
"前端组件",
"通用组件"
],
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "https://www.npmjs.com/package/@dcloudio/uni-ui"
},
"uni_modules": {
"dependencies": [
"uni-scss",
"uni-icons"
],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y"
},
"client": {
"App": {
"app-vue": "y",
"app-nvue": "n"
},
"H5-mobile": {
"Safari": "y",
"Android Browser": "y",
"微信浏览器(Android)": "y",
"QQ浏览器(Android)": "y"
},
"H5-pc": {
"Chrome": "y",
"IE": "y",
"Edge": "y",
"Firefox": "y",
"Safari": "y"
},
"小程序": {
"微信": "y",
"阿里": "y",
"百度": "y",
"字节跳动": "y",
"QQ": "y"
},
"快应用": {
"华为": "u",
"联盟": "u"
},
"Vue": {
"vue2": "y",
"vue3": "y"
}
}
}
}
}
+11
View File
@@ -0,0 +1,11 @@
## Combox 组合框
> **组件名:uni-combox**
> 代码块: `uCombox`
组合框组件。
### [查看文档](https://uniapp.dcloud.io/component/uniui/uni-combox)
#### 如使用过程中有任何问题,或者您对uni-ui有一些好的建议,欢迎加入 uni-ui 交流群:871950839
@@ -0,0 +1,26 @@
## 1.2.3(2024-02-20)
- 新增 支持控制小时,分钟的显隐:showHour showMinute
## 1.2.2(2022-01-19)
- 修复 在微信小程序中样式不生效的bug
## 1.2.1(2022-01-18)
- 新增 update 方法 ,在动态更新时间后,刷新组件
## 1.2.0(2021-11-19)
- 优化 组件UI,并提供设计资源,详见:[https://uniapp.dcloud.io/component/uniui/resource](https://uniapp.dcloud.io/component/uniui/resource)
- 文档迁移,详见:[https://uniapp.dcloud.io/component/uniui/uni-countdown](https://uniapp.dcloud.io/component/uniui/uni-countdown)
## 1.1.3(2021-10-18)
- 重构
- 新增 font-size 支持自定义字体大小
## 1.1.2(2021-08-24)
- 新增 支持国际化
## 1.1.1(2021-07-30)
- 优化 vue3下小程序事件警告的问题
## 1.1.0(2021-07-30)
- 组件兼容 vue3,如何创建vue3项目,详见 [uni-app 项目支持 vue3 介绍](https://ask.dcloud.net.cn/article/37834)
## 1.0.5(2021-06-18)
- 修复 uni-countdown 重复赋值跳两秒的 bug
## 1.0.4(2021-05-12)
- 新增 组件示例地址
## 1.0.3(2021-05-08)
- 修复 uni-countdown 不能控制倒计时的 bug
## 1.0.2(2021-02-04)
- 调整为uni_modules目录规范
@@ -0,0 +1,6 @@
{
"uni-countdown.day": "day",
"uni-countdown.h": "h",
"uni-countdown.m": "m",
"uni-countdown.s": "s"
}
@@ -0,0 +1,8 @@
import en from './en.json'
import zhHans from './zh-Hans.json'
import zhHant from './zh-Hant.json'
export default {
en,
'zh-Hans': zhHans,
'zh-Hant': zhHant
}
@@ -0,0 +1,6 @@
{
"uni-countdown.day": "天",
"uni-countdown.h": "时",
"uni-countdown.m": "分",
"uni-countdown.s": "秒"
}
@@ -0,0 +1,6 @@
{
"uni-countdown.day": "天",
"uni-countdown.h": "時",
"uni-countdown.m": "分",
"uni-countdown.s": "秒"
}
@@ -0,0 +1,281 @@
<template>
<view class="uni-countdown">
<text v-if="showDay" :style="[timeStyle]" class="uni-countdown__number">{{ d }}</text>
<text v-if="showDay" :style="[splitorStyle]" class="uni-countdown__splitor">{{dayText}}</text>
<text v-if="showHour" :style="[timeStyle]" class="uni-countdown__number">{{ h }}</text>
<text v-if="showHour" :style="[splitorStyle]" class="uni-countdown__splitor">{{ showColon ? ':' : hourText }}</text>
<text v-if="showMinute" :style="[timeStyle]" class="uni-countdown__number">{{ i }}</text>
<text v-if="showMinute" :style="[splitorStyle]" class="uni-countdown__splitor">{{ showColon ? ':' : minuteText }}</text>
<text :style="[timeStyle]" class="uni-countdown__number">{{ s }}</text>
<text v-if="!showColon" :style="[splitorStyle]" class="uni-countdown__splitor">{{secondText}}</text>
</view>
</template>
<script>
import {
initVueI18n
} from '@dcloudio/uni-i18n'
import messages from './i18n/index.js'
const {
t
} = initVueI18n(messages)
/**
* Countdown 倒计时
* @description 倒计时组件
* @tutorial https://ext.dcloud.net.cn/plugin?id=25
* @property {String} backgroundColor 背景色
* @property {String} color 文字颜色
* @property {Number} day 天数
* @property {Number} hour 小时
* @property {Number} minute 分钟
* @property {Number} second 秒
* @property {Number} timestamp 时间戳
* @property {Boolean} showDay = [true|false] 是否显示天数
* @property {Boolean} showHour = [true|false] 是否显示小时
* @property {Boolean} showMinute = [true|false] 是否显示分钟
* @property {Boolean} show-colon = [true|false] 是否以冒号为分隔符
* @property {String} splitorColor 分割符号颜色
* @event {Function} timeup 倒计时时间到触发事件
* @example <uni-countdown :day="1" :hour="1" :minute="12" :second="40"></uni-countdown>
*/
export default {
name: 'UniCountdown',
emits: ['timeup'],
props: {
showDay: {
type: Boolean,
default: true
},
showHour: {
type: Boolean,
default: true
},
showMinute: {
type: Boolean,
default: true
},
showColon: {
type: Boolean,
default: true
},
start: {
type: Boolean,
default: true
},
backgroundColor: {
type: String,
default: ''
},
color: {
type: String,
default: '#333'
},
fontSize: {
type: Number,
default: 14
},
splitorColor: {
type: String,
default: '#333'
},
day: {
type: Number,
default: 0
},
hour: {
type: Number,
default: 0
},
minute: {
type: Number,
default: 0
},
second: {
type: Number,
default: 0
},
timestamp: {
type: Number,
default: 0
}
},
data() {
return {
timer: null,
syncFlag: false,
d: '00',
h: '00',
i: '00',
s: '00',
leftTime: 0,
seconds: 0
}
},
computed: {
dayText() {
return t("uni-countdown.day")
},
hourText(val) {
return t("uni-countdown.h")
},
minuteText(val) {
return t("uni-countdown.m")
},
secondText(val) {
return t("uni-countdown.s")
},
timeStyle() {
const {
color,
backgroundColor,
fontSize
} = this
return {
color,
backgroundColor,
fontSize: `${fontSize}px`,
width: `${fontSize * 22 / 14}px`, // 按字体大小为 14px 时的比例缩放
lineHeight: `${fontSize * 20 / 14}px`,
borderRadius: `${fontSize * 3 / 14}px`,
}
},
splitorStyle() {
const { splitorColor, fontSize, backgroundColor } = this
return {
color: splitorColor,
fontSize: `${fontSize * 12 / 14}px`,
margin: backgroundColor ? `${fontSize * 4 / 14}px` : ''
}
}
},
watch: {
day(val) {
this.changeFlag()
},
hour(val) {
this.changeFlag()
},
minute(val) {
this.changeFlag()
},
second(val) {
this.changeFlag()
},
start: {
immediate: true,
handler(newVal, oldVal) {
if (newVal) {
this.startData();
} else {
if (!oldVal) return
clearInterval(this.timer)
}
}
}
},
created: function(e) {
this.seconds = this.toSeconds(this.timestamp, this.day, this.hour, this.minute, this.second)
this.countDown()
},
// #ifndef VUE3
destroyed() {
clearInterval(this.timer)
},
// #endif
// #ifdef VUE3
unmounted() {
clearInterval(this.timer)
},
// #endif
methods: {
toSeconds(timestamp, day, hours, minutes, seconds) {
if (timestamp) {
return timestamp - parseInt(new Date().getTime() / 1000, 10)
}
return day * 60 * 60 * 24 + hours * 60 * 60 + minutes * 60 + seconds
},
timeUp() {
clearInterval(this.timer)
this.$emit('timeup')
},
countDown() {
let seconds = this.seconds
let [day, hour, minute, second] = [0, 0, 0, 0]
if (seconds > 0) {
day = Math.floor(seconds / (60 * 60 * 24))
hour = Math.floor(seconds / (60 * 60)) - (day * 24)
minute = Math.floor(seconds / 60) - (day * 24 * 60) - (hour * 60)
second = Math.floor(seconds) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60)
} else {
this.timeUp()
}
if (day < 10) {
day = '0' + day
}
if (hour < 10) {
hour = '0' + hour
}
if (minute < 10) {
minute = '0' + minute
}
if (second < 10) {
second = '0' + second
}
this.d = day
this.h = hour
this.i = minute
this.s = second
},
startData() {
this.seconds = this.toSeconds(this.timestamp, this.day, this.hour, this.minute, this.second)
if (this.seconds <= 0) {
this.seconds = this.toSeconds(0, 0, 0, 0, 0)
this.countDown()
return
}
clearInterval(this.timer)
this.countDown()
this.timer = setInterval(() => {
this.seconds--
if (this.seconds < 0) {
this.timeUp()
return
}
this.countDown()
}, 1000)
},
update(){
this.startData();
},
changeFlag() {
if (!this.syncFlag) {
this.seconds = this.toSeconds(this.timestamp, this.day, this.hour, this.minute, this.second)
this.startData();
this.syncFlag = true;
}
}
}
}
</script>
<style lang="scss" scoped>
$font-size: 14px;
.uni-countdown {
display: flex;
flex-direction: row;
justify-content: flex-start;
align-items: center;
&__splitor {
margin: 0 2px;
font-size: $font-size;
color: #333;
}
&__number {
border-radius: 3px;
text-align: center;
font-size: $font-size;
}
}
</style>
@@ -0,0 +1,83 @@
{
"id": "uni-countdown",
"displayName": "uni-countdown 倒计时",
"version": "1.2.3",
"description": "CountDown 倒计时组件",
"keywords": [
"uni-ui",
"uniui",
"countdown",
"倒计时"
],
"repository": "https://github.com/dcloudio/uni-ui",
"engines": {
"HBuilderX": ""
},
"directories": {
"example": "../../temps/example_temps"
},
"dcloudext": {
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "https://www.npmjs.com/package/@dcloudio/uni-ui",
"type": "component-vue"
},
"uni_modules": {
"dependencies": ["uni-scss"],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y"
},
"client": {
"App": {
"app-vue": "y",
"app-nvue": "y"
},
"H5-mobile": {
"Safari": "y",
"Android Browser": "y",
"微信浏览器(Android)": "y",
"QQ浏览器(Android)": "y"
},
"H5-pc": {
"Chrome": "y",
"IE": "y",
"Edge": "y",
"Firefox": "y",
"Safari": "y"
},
"小程序": {
"微信": "y",
"阿里": "y",
"百度": "y",
"字节跳动": "y",
"QQ": "y"
},
"快应用": {
"华为": "u",
"联盟": "u"
},
"Vue": {
"vue2": "y",
"vue3": "y"
}
}
}
}
}
@@ -0,0 +1,10 @@
## CountDown 倒计时
> **组件名:uni-countdown**
> 代码块: `uCountDown`
倒计时组件。
### [查看文档](https://uniapp.dcloud.io/component/uniui/uni-countdown)
#### 如使用过程中有任何问题,或者您对uni-ui有一些好的建议,欢迎加入 uni-ui 交流群:871950839
@@ -0,0 +1,49 @@
## 1.0.5(2024-03-20)
- 修复 单选模式下选中样式不生效的bug
## 1.0.4(2024-01-27)
- 修复 修复错别字chagne为change
## 1.0.3(2022-09-16)
- 可以使用 uni-scss 控制主题色
## 1.0.2(2022-06-30)
- 优化 在 uni-forms 中的依赖注入方式
## 1.0.1(2022-02-07)
- 修复 multiple 为 true 时,v-model 的值为 null 报错的 bug
## 1.0.0(2021-11-19)
- 优化 组件UI,并提供设计资源,详见:[https://uniapp.dcloud.io/component/uniui/resource](https://uniapp.dcloud.io/component/uniui/resource)
- 文档迁移,详见:[https://uniapp.dcloud.io/component/uniui/uni-data-checkbox](https://uniapp.dcloud.io/component/uniui/uni-data-checkbox)
## 0.2.5(2021-08-23)
- 修复 在uni-forms中 modelValue 中不存在当前字段,当前字段必填写也不参与校验的问题
## 0.2.4(2021-08-17)
- 修复 单选 list 模式下 ,icon 为 left 时,选中图标不显示的问题
## 0.2.3(2021-08-11)
- 修复 在 uni-forms 中重置表单,错误信息无法清除的问题
## 0.2.2(2021-07-30)
- 优化 在uni-forms组件,与label不对齐的问题
## 0.2.1(2021-07-27)
- 修复 单选默认值为0不能选中的Bug
## 0.2.0(2021-07-13)
- 组件兼容 vue3,如何创建vue3项目,详见 [uni-app 项目支持 vue3 介绍](https://ask.dcloud.net.cn/article/37834)
## 0.1.11(2021-07-06)
- 优化 删除无用日志
## 0.1.10(2021-07-05)
- 修复 由 0.1.9 引起的非 nvue 端图标不显示的问题
## 0.1.9(2021-07-05)
- 修复 nvue 黑框样式问题
## 0.1.8(2021-06-28)
- 修复 selectedTextColor 属性不生效的Bug
## 0.1.7(2021-06-02)
- 新增 map 属性,可以方便映射text/value属性
## 0.1.6(2021-05-26)
- 修复 不关联服务空间的情况下组件报错的Bug
## 0.1.5(2021-05-12)
- 新增 组件示例地址
## 0.1.4(2021-04-09)
- 修复 nvue 下无法选中的问题
## 0.1.3(2021-03-22)
- 新增 disabled属性
## 0.1.2(2021-02-24)
- 优化 默认颜色显示
## 0.1.1(2021-02-24)
- 新增 支持nvue
## 0.1.0(2021-02-18)
- “暂无数据”显示居中
@@ -0,0 +1,849 @@
<template>
<view class="uni-data-checklist" :style="{'margin-top':isTop+'px'}">
<template v-if="!isLocal">
<view class="uni-data-loading">
<uni-load-more v-if="!mixinDatacomErrorMessage" status="loading" iconType="snow" :iconSize="18"
:content-text="contentText"></uni-load-more>
<text v-else>{{mixinDatacomErrorMessage}}</text>
</view>
</template>
<template v-else>
<checkbox-group v-if="multiple" class="checklist-group" :class="{'is-list':mode==='list' || wrap}"
@change="change">
<label class="checklist-box"
:class="['is--'+mode,item.selected?'is-checked':'',(disabled || !!item.disabled)?'is-disable':'',index!==0&&mode==='list'?'is-list-border':'']"
:style="item.styleBackgroud" v-for="(item,index) in dataList" :key="index">
<checkbox class="hidden" hidden :disabled="disabled || !!item.disabled" :value="item[map.value]+''"
:checked="item.selected" />
<view v-if="(mode !=='tag' && mode !== 'list') || ( mode === 'list' && icon === 'left')"
class="checkbox__inner" :style="item.styleIcon">
<view class="checkbox__inner-icon"></view>
</view>
<view class="checklist-content" :class="{'list-content':mode === 'list' && icon ==='left'}">
<text class="checklist-text" :style="item.styleIconText">{{item[map.text]}}</text>
<view v-if="mode === 'list' && icon === 'right'" class="checkobx__list" :style="item.styleBackgroud"></view>
</view>
</label>
</checkbox-group>
<radio-group v-else class="checklist-group" :class="{'is-list':mode==='list','is-wrap':wrap}" @change="change">
<label class="checklist-box"
:class="['is--'+mode,item.selected?'is-checked':'',(disabled || !!item.disabled)?'is-disable':'',index!==0&&mode==='list'?'is-list-border':'']"
:style="item.styleBackgroud" v-for="(item,index) in dataList" :key="index">
<radio class="hidden" hidden :disabled="disabled || item.disabled" :value="item[map.value]+''"
:checked="item.selected" />
<view v-if="(mode !=='tag' && mode !== 'list') || ( mode === 'list' && icon === 'left')" class="radio__inner"
:style="item.styleBackgroud">
<view class="radio__inner-icon" :style="item.styleIcon"></view>
</view>
<view class="checklist-content" :class="{'list-content':mode === 'list' && icon ==='left'}">
<text class="checklist-text" :style="item.styleIconText">{{item[map.text]}}</text>
<view v-if="mode === 'list' && icon === 'right'" :style="item.styleRightIcon" class="checkobx__list"></view>
</view>
</label>
</radio-group>
</template>
</view>
</template>
<script>
/**
* DataChecklist 数据选择器
* @description 通过数据渲染 checkbox 和 radio
* @tutorial https://ext.dcloud.net.cn/plugin?id=xxx
* @property {String} mode = [default| list | button | tag] 显示模式
* @value default 默认横排模式
* @value list 列表模式
* @value button 按钮模式
* @value tag 标签模式
* @property {Boolean} multiple = [true|false] 是否多选
* @property {Array|String|Number} value 默认值
* @property {Array} localdata 本地数据 ,格式 [{text:'',value:''}]
* @property {Number|String} min 最小选择个数 ,multiple为true时生效
* @property {Number|String} max 最大选择个数 ,multiple为true时生效
* @property {Boolean} wrap 是否换行显示
* @property {String} icon = [left|right] list 列表模式下icon显示位置
* @property {Boolean} selectedColor 选中颜色
* @property {Boolean} emptyText 没有数据时显示的文字 ,本地数据无效
* @property {Boolean} selectedTextColor 选中文本颜色,如不填写则自动显示
* @property {Object} map 字段映射, 默认 map={text:'text',value:'value'}
* @value left 左侧显示
* @value right 右侧显示
* @event {Function} change 选中发生变化触发
*/
export default {
name: 'uniDataChecklist',
mixins: [uniCloud.mixinDatacom || {}],
emits: ['input', 'update:modelValue', 'change'],
props: {
mode: {
type: String,
default: 'default'
},
multiple: {
type: Boolean,
default: false
},
value: {
type: [Array, String, Number],
default () {
return ''
}
},
// TODO vue3
modelValue: {
type: [Array, String, Number],
default () {
return '';
}
},
localdata: {
type: Array,
default () {
return []
}
},
min: {
type: [Number, String],
default: ''
},
max: {
type: [Number, String],
default: ''
},
wrap: {
type: Boolean,
default: false
},
icon: {
type: String,
default: 'left'
},
selectedColor: {
type: String,
default: ''
},
selectedTextColor: {
type: String,
default: ''
},
emptyText: {
type: String,
default: '暂无数据'
},
disabled: {
type: Boolean,
default: false
},
map: {
type: Object,
default () {
return {
text: 'text',
value: 'value'
}
}
}
},
watch: {
localdata: {
handler(newVal) {
this.range = newVal
this.dataList = this.getDataList(this.getSelectedValue(newVal))
},
deep: true
},
mixinDatacomResData(newVal) {
this.range = newVal
this.dataList = this.getDataList(this.getSelectedValue(newVal))
},
value(newVal) {
this.dataList = this.getDataList(newVal)
// fix by mehaotian is_reset 在 uni-forms 中定义
// if(!this.is_reset){
// this.is_reset = false
// this.formItem && this.formItem.setValue(newVal)
// }
},
modelValue(newVal) {
this.dataList = this.getDataList(newVal);
// if(!this.is_reset){
// this.is_reset = false
// this.formItem && this.formItem.setValue(newVal)
// }
}
},
data() {
return {
dataList: [],
range: [],
contentText: {
contentdown: '查看更多',
contentrefresh: '加载中',
contentnomore: '没有更多'
},
isLocal: true,
styles: {
selectedColor: '#2979ff',
selectedTextColor: '#666',
},
isTop: 0
};
},
computed: {
dataValue() {
if (this.value === '') return this.modelValue
if (this.modelValue === '') return this.value
return this.value
}
},
created() {
// this.form = this.getForm('uniForms')
// this.formItem = this.getForm('uniFormsItem')
// this.formItem && this.formItem.setValue(this.value)
// if (this.formItem) {
// this.isTop = 6
// if (this.formItem.name) {
// // 如果存在name添加默认值,否则formData 中不存在这个字段不校验
// if(!this.is_reset){
// this.is_reset = false
// this.formItem.setValue(this.dataValue)
// }
// this.rename = this.formItem.name
// this.form.inputChildrens.push(this)
// }
// }
if (this.localdata && this.localdata.length !== 0) {
this.isLocal = true
this.range = this.localdata
this.dataList = this.getDataList(this.getSelectedValue(this.range))
} else {
if (this.collection) {
this.isLocal = false
this.loadData()
}
}
},
methods: {
loadData() {
this.mixinDatacomGet().then(res => {
this.mixinDatacomResData = res.result.data
if (this.mixinDatacomResData.length === 0) {
this.isLocal = false
this.mixinDatacomErrorMessage = this.emptyText
} else {
this.isLocal = true
}
}).catch(err => {
this.mixinDatacomErrorMessage = err.message
})
},
/**
* 获取父元素实例
*/
getForm(name = 'uniForms') {
let parent = this.$parent;
let parentName = parent.$options.name;
while (parentName !== name) {
parent = parent.$parent;
if (!parent) return false
parentName = parent.$options.name;
}
return parent;
},
change(e) {
const values = e.detail.value
let detail = {
value: [],
data: []
}
if (this.multiple) {
this.range.forEach(item => {
if (values.includes(item[this.map.value] + '')) {
detail.value.push(item[this.map.value])
detail.data.push(item)
}
})
} else {
const range = this.range.find(item => (item[this.map.value] + '') === values)
if (range) {
detail = {
value: range[this.map.value],
data: range
}
}
}
// this.formItem && this.formItem.setValue(detail.value)
// TODO 兼容 vue2
this.$emit('input', detail.value);
// // TOTO 兼容 vue3
this.$emit('update:modelValue', detail.value);
this.$emit('change', {
detail
})
if (this.multiple) {
// 如果 v-model 没有绑定 ,则走内部逻辑
// if (this.value.length === 0) {
this.dataList = this.getDataList(detail.value, true)
// }
} else {
this.dataList = this.getDataList(detail.value)
}
},
/**
* 获取渲染的新数组
* @param {Object} value 选中内容
*/
getDataList(value) {
// 解除引用关系,破坏原引用关系,避免污染源数据
let dataList = JSON.parse(JSON.stringify(this.range))
let list = []
if (this.multiple) {
if (!Array.isArray(value)) {
value = []
}
}
dataList.forEach((item, index) => {
item.disabled = item.disable || item.disabled || false
if (this.multiple) {
if (value.length > 0) {
let have = value.find(val => val === item[this.map.value])
item.selected = have !== undefined
} else {
item.selected = false
}
} else {
item.selected = value === item[this.map.value]
}
list.push(item)
})
return this.setRange(list)
},
/**
* 处理最大最小值
* @param {Object} list
*/
setRange(list) {
let selectList = list.filter(item => item.selected)
let min = Number(this.min) || 0
let max = Number(this.max) || ''
list.forEach((item, index) => {
if (this.multiple) {
if (selectList.length <= min) {
let have = selectList.find(val => val[this.map.value] === item[this.map.value])
if (have !== undefined) {
item.disabled = true
}
}
if (selectList.length >= max && max !== '') {
let have = selectList.find(val => val[this.map.value] === item[this.map.value])
if (have === undefined) {
item.disabled = true
}
}
}
this.setStyles(item, index)
list[index] = item
})
return list
},
/**
* 设置 class
* @param {Object} item
* @param {Object} index
*/
setStyles(item, index) {
// 设置自定义样式
item.styleBackgroud = this.setStyleBackgroud(item)
item.styleIcon = this.setStyleIcon(item)
item.styleIconText = this.setStyleIconText(item)
item.styleRightIcon = this.setStyleRightIcon(item)
},
/**
* 获取选中值
* @param {Object} range
*/
getSelectedValue(range) {
if (!this.multiple) return this.dataValue
let selectedArr = []
range.forEach((item) => {
if (item.selected) {
selectedArr.push(item[this.map.value])
}
})
return this.dataValue.length > 0 ? this.dataValue : selectedArr
},
/**
* 设置背景样式
*/
setStyleBackgroud(item) {
let styles = {}
let selectedColor = this.selectedColor ? this.selectedColor : '#2979ff'
if (this.selectedColor) {
if (this.mode !== 'list') {
styles['border-color'] = item.selected ? selectedColor : '#DCDFE6'
}
if (this.mode === 'tag') {
styles['background-color'] = item.selected ? selectedColor : '#f5f5f5'
}
}
let classles = ''
for (let i in styles) {
classles += `${i}:${styles[i]};`
}
return classles
},
setStyleIcon(item) {
let styles = {}
let classles = ''
if (this.selectedColor) {
let selectedColor = this.selectedColor ? this.selectedColor : '#2979ff'
styles['background-color'] = item.selected ? selectedColor : '#fff'
styles['border-color'] = item.selected ? selectedColor : '#DCDFE6'
if (!item.selected && item.disabled) {
styles['background-color'] = '#F2F6FC'
styles['border-color'] = item.selected ? selectedColor : '#DCDFE6'
}
}
for (let i in styles) {
classles += `${i}:${styles[i]};`
}
return classles
},
setStyleIconText(item) {
let styles = {}
let classles = ''
if (this.selectedColor) {
let selectedColor = this.selectedColor ? this.selectedColor : '#2979ff'
if (this.mode === 'tag') {
styles.color = item.selected ? (this.selectedTextColor ? this.selectedTextColor : '#fff') : '#666'
} else {
styles.color = item.selected ? (this.selectedTextColor ? this.selectedTextColor : selectedColor) : '#666'
}
if (!item.selected && item.disabled) {
styles.color = '#999'
}
}
for (let i in styles) {
classles += `${i}:${styles[i]};`
}
return classles
},
setStyleRightIcon(item) {
let styles = {}
let classles = ''
if (this.mode === 'list') {
styles['border-color'] = item.selected ? this.styles.selectedColor : '#DCDFE6'
}
for (let i in styles) {
classles += `${i}:${styles[i]};`
}
return classles
}
}
}
</script>
<style lang="scss">
$uni-primary: #2979ff !default;
$border-color: #DCDFE6;
$disable: 0.4;
@mixin flex {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
}
.uni-data-loading {
@include flex;
flex-direction: row;
justify-content: center;
align-items: center;
height: 36px;
padding-left: 10px;
color: #999;
}
.uni-data-checklist {
position: relative;
z-index: 0;
flex: 1;
// 多选样式
.checklist-group {
@include flex;
flex-direction: row;
flex-wrap: wrap;
&.is-list {
flex-direction: column;
}
.checklist-box {
@include flex;
flex-direction: row;
align-items: center;
position: relative;
margin: 5px 0;
margin-right: 25px;
.hidden {
position: absolute;
opacity: 0;
}
// 文字样式
.checklist-content {
@include flex;
flex: 1;
flex-direction: row;
align-items: center;
justify-content: space-between;
.checklist-text {
font-size: 14px;
color: #666;
margin-left: 5px;
line-height: 14px;
}
.checkobx__list {
border-right-width: 1px;
border-right-color: #007aff;
border-right-style: solid;
border-bottom-width: 1px;
border-bottom-color: #007aff;
border-bottom-style: solid;
height: 12px;
width: 6px;
left: -5px;
transform-origin: center;
transform: rotate(45deg);
opacity: 0;
}
}
// 多选样式
.checkbox__inner {
/* #ifndef APP-NVUE */
flex-shrink: 0;
box-sizing: border-box;
/* #endif */
position: relative;
width: 16px;
height: 16px;
border: 1px solid $border-color;
border-radius: 4px;
background-color: #fff;
z-index: 1;
.checkbox__inner-icon {
position: absolute;
/* #ifdef APP-NVUE */
top: 2px;
/* #endif */
/* #ifndef APP-NVUE */
top: 1px;
/* #endif */
left: 5px;
height: 8px;
width: 4px;
border-right-width: 1px;
border-right-color: #fff;
border-right-style: solid;
border-bottom-width: 1px;
border-bottom-color: #fff;
border-bottom-style: solid;
opacity: 0;
transform-origin: center;
transform: rotate(40deg);
}
}
// 单选样式
.radio__inner {
@include flex;
/* #ifndef APP-NVUE */
flex-shrink: 0;
box-sizing: border-box;
/* #endif */
justify-content: center;
align-items: center;
position: relative;
width: 16px;
height: 16px;
border: 1px solid $border-color;
border-radius: 16px;
background-color: #fff;
z-index: 1;
.radio__inner-icon {
width: 8px;
height: 8px;
border-radius: 10px;
opacity: 0;
}
}
// 默认样式
&.is--default {
// 禁用
&.is-disable {
/* #ifdef H5 */
cursor: not-allowed;
/* #endif */
.checkbox__inner {
background-color: #F2F6FC;
border-color: $border-color;
/* #ifdef H5 */
cursor: not-allowed;
/* #endif */
}
.radio__inner {
background-color: #F2F6FC;
border-color: $border-color;
}
.checklist-text {
color: #999;
}
}
// 选中
&.is-checked {
.checkbox__inner {
border-color: $uni-primary;
background-color: $uni-primary;
.checkbox__inner-icon {
opacity: 1;
transform: rotate(45deg);
}
}
.radio__inner {
border-color: $uni-primary;
.radio__inner-icon {
opacity: 1;
background-color: $uni-primary;
}
}
.checklist-text {
color: $uni-primary;
}
// 选中禁用
&.is-disable {
.checkbox__inner {
opacity: $disable;
}
.checklist-text {
opacity: $disable;
}
.radio__inner {
opacity: $disable;
}
}
}
}
// 按钮样式
&.is--button {
margin-right: 10px;
padding: 5px 10px;
border: 1px $border-color solid;
border-radius: 3px;
transition: border-color 0.2s;
// 禁用
&.is-disable {
/* #ifdef H5 */
cursor: not-allowed;
/* #endif */
border: 1px #eee solid;
opacity: $disable;
.checkbox__inner {
background-color: #F2F6FC;
border-color: $border-color;
/* #ifdef H5 */
cursor: not-allowed;
/* #endif */
}
.radio__inner {
background-color: #F2F6FC;
border-color: $border-color;
/* #ifdef H5 */
cursor: not-allowed;
/* #endif */
}
.checklist-text {
color: #999;
}
}
&.is-checked {
border-color: $uni-primary;
.checkbox__inner {
border-color: $uni-primary;
background-color: $uni-primary;
.checkbox__inner-icon {
opacity: 1;
transform: rotate(45deg);
}
}
.radio__inner {
border-color: $uni-primary;
.radio__inner-icon {
opacity: 1;
background-color: $uni-primary;
}
}
.checklist-text {
color: $uni-primary;
}
// 选中禁用
&.is-disable {
opacity: $disable;
}
}
}
// 标签样式
&.is--tag {
margin-right: 10px;
padding: 5px 10px;
border: 1px $border-color solid;
border-radius: 3px;
background-color: #f5f5f5;
.checklist-text {
margin: 0;
color: #666;
}
// 禁用
&.is-disable {
/* #ifdef H5 */
cursor: not-allowed;
/* #endif */
opacity: $disable;
}
&.is-checked {
background-color: $uni-primary;
border-color: $uni-primary;
.checklist-text {
color: #fff;
}
}
}
// 列表样式
&.is--list {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
padding: 10px 15px;
padding-left: 0;
margin: 0;
&.is-list-border {
border-top: 1px #eee solid;
}
// 禁用
&.is-disable {
/* #ifdef H5 */
cursor: not-allowed;
/* #endif */
.checkbox__inner {
background-color: #F2F6FC;
border-color: $border-color;
/* #ifdef H5 */
cursor: not-allowed;
/* #endif */
}
.checklist-text {
color: #999;
}
}
&.is-checked {
.checkbox__inner {
border-color: $uni-primary;
background-color: $uni-primary;
.checkbox__inner-icon {
opacity: 1;
transform: rotate(45deg);
}
}
.radio__inner {
border-color: $uni-primary;
.radio__inner-icon {
opacity: 1;
background-color: $uni-primary;
}
}
.checklist-text {
color: $uni-primary;
}
.checklist-content {
.checkobx__list {
opacity: 1;
border-color: $uni-primary;
}
}
// 选中禁用
&.is-disable {
.checkbox__inner {
opacity: $disable;
}
.checklist-text {
opacity: $disable;
}
}
}
}
}
}
}
</style>
@@ -0,0 +1,84 @@
{
"id": "uni-data-checkbox",
"displayName": "uni-data-checkbox 数据选择器",
"version": "1.0.5",
"description": "通过数据驱动的单选框和复选框",
"keywords": [
"uni-ui",
"checkbox",
"单选",
"多选",
"单选多选"
],
"repository": "https://github.com/dcloudio/uni-ui",
"engines": {
"HBuilderX": "^3.1.1"
},
"directories": {
"example": "../../temps/example_temps"
},
"dcloudext": {
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "https://www.npmjs.com/package/@dcloudio/uni-ui",
"type": "component-vue"
},
"uni_modules": {
"dependencies": ["uni-load-more","uni-scss"],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y"
},
"client": {
"App": {
"app-vue": "y",
"app-nvue": "y"
},
"H5-mobile": {
"Safari": "y",
"Android Browser": "y",
"微信浏览器(Android)": "y",
"QQ浏览器(Android)": "y"
},
"H5-pc": {
"Chrome": "y",
"IE": "y",
"Edge": "y",
"Firefox": "y",
"Safari": "y"
},
"小程序": {
"微信": "y",
"阿里": "y",
"百度": "y",
"字节跳动": "y",
"QQ": "y"
},
"快应用": {
"华为": "u",
"联盟": "u"
},
"Vue": {
"vue2": "y",
"vue3": "y"
}
}
}
}
}
@@ -0,0 +1,18 @@
## DataCheckbox 数据驱动的单选复选框
> **组件名:uni-data-checkbox**
> 代码块: `uDataCheckbox`
本组件是基于uni-app基础组件checkbox的封装。本组件要解决问题包括:
1. 数据绑定型组件:给本组件绑定一个data,会自动渲染一组候选内容。再以往,开发者需要编写不少代码实现类似功能
2. 自动的表单校验:组件绑定了data,且符合[uni-forms](https://ext.dcloud.net.cn/plugin?id=2773)组件的表单校验规范,搭配使用会自动实现表单校验
3. 本组件合并了单选多选
4. 本组件有若干风格选择,如普通的单选多选框、并列button风格、tag风格。开发者可以快速选择需要的风格。但作为一个封装组件,样式代码虽然不用自己写了,却会牺牲一定的样式自定义性
在uniCloud开发中,`DB Schema`中配置了enum枚举等类型后,在web控制台的[自动生成表单](https://uniapp.dcloud.io/uniCloud/schema?id=autocode)功能中,会自动生成``uni-data-checkbox``组件并绑定好data
### [查看文档](https://uniapp.dcloud.io/component/uniui/uni-data-checkbox)
#### 如使用过程中有任何问题,或者您对uni-ui有一些好的建议,欢迎加入 uni-ui 交流群:871950839
@@ -0,0 +1,77 @@
## 2.0.0(2023-12-14)
- 新增 支持 uni-app-x
## 1.1.2(2023-04-11)
- 修复 更改 modelValue 报错的 bug
- 修复 v-for 未使用 key 值控制台 warning
## 1.1.1(2023-02-21)
- 修复代码合并时引发 value 属性为空时不渲染数据的问题
## 1.1.0(2023-02-15)
- 修复 localdata 不支持动态更新的bug
## 1.0.9(2023-02-15)
- 修复 localdata 不支持动态更新的bug
## 1.0.8(2022-09-16)
- 可以使用 uni-scss 控制主题色
## 1.0.7(2022-07-06)
- 优化 pc端图标位置不正确的问题
## 1.0.6(2022-07-05)
- 优化 显示样式
## 1.0.5(2022-07-04)
- 修复 uni-data-picker 在 uni-forms-item 中宽度不正确的bug
## 1.0.4(2022-04-19)
- 修复 字节小程序 本地数据无法选择下一级的Bug
## 1.0.3(2022-02-25)
- 修复 nvue 不支持的 v-show 的 bug
## 1.0.2(2022-02-25)
- 修复 条件编译 nvue 不支持的 css 样式
## 1.0.1(2021-11-23)
- 修复 由上个版本引发的map、v-model等属性不生效的bug
## 1.0.0(2021-11-19)
- 优化 组件 UI,并提供设计资源,详见:[https://uniapp.dcloud.io/component/uniui/resource](https://uniapp.dcloud.io/component/uniui/resource)
- 文档迁移,详见:[https://uniapp.dcloud.io/component/uniui/uni-data-picker](https://uniapp.dcloud.io/component/uniui/uni-data-picker)
## 0.4.9(2021-10-28)
- 修复 VUE2 v-model 概率无效的 bug
## 0.4.8(2021-10-27)
- 修复 v-model 概率无效的 bug
## 0.4.7(2021-10-25)
- 新增 属性 spaceInfo 服务空间配置 HBuilderX 3.2.11+
- 修复 树型 uniCloud 数据类型为 int 时报错的 bug
## 0.4.6(2021-10-19)
- 修复 非 VUE3 v-model 为 0 时无法选中的 bug
## 0.4.5(2021-09-26)
- 新增 清除已选项的功能(通过 clearIcon 属性配置是否显示按钮),同时提供 clear 方法以供调用,二者等效
- 修复 readonly 为 true 时报错的 bug
## 0.4.4(2021-09-26)
- 修复 上一版本造成的 map 属性失效的 bug
- 新增 ellipsis 属性,支持配置 tab 选项长度过长时是否自动省略
## 0.4.3(2021-09-24)
- 修复 某些情况下级联未触发的 bug
## 0.4.2(2021-09-23)
- 新增 提供 show 和 hide 方法,开发者可以通过 ref 调用
- 新增 选项内容过长自动添加省略号
## 0.4.1(2021-09-15)
- 新增 map 属性 字段映射,将 text/value 映射到数据中的其他字段
## 0.4.0(2021-07-13)
- 组件兼容 vue3,如何创建 vue3 项目,详见 [uni-app 项目支持 vue3 介绍](https://ask.dcloud.net.cn/article/37834)
## 0.3.5(2021-06-04)
- 修复 无法加载云端数据的问题
## 0.3.4(2021-05-28)
- 修复 v-model 无效问题
- 修复 loaddata 为空数据组时加载时间过长问题
- 修复 上个版本引出的本地数据无法选择带有 children 的 2 级节点
## 0.3.3(2021-05-12)
- 新增 组件示例地址
## 0.3.2(2021-04-22)
- 修复 非树形数据有 where 属性查询报错的问题
## 0.3.1(2021-04-15)
- 修复 本地数据概率无法回显时问题
## 0.3.0(2021-04-07)
- 新增 支持云端非树形表结构数据
- 修复 根节点 parent_field 字段等于 null 时选择界面错乱问题
## 0.2.0(2021-03-15)
- 修复 nodeclick、popupopened、popupclosed 事件无法触发的问题
## 0.1.9(2021-03-09)
- 修复 微信小程序某些情况下无法选择的问题
## 0.1.8(2021-02-05)
- 优化 部分样式在 nvue 上的兼容表现
## 0.1.7(2021-02-05)
- 调整为 uni_modules 目录规范
@@ -0,0 +1,45 @@
// #ifdef H5
export default {
name: 'Keypress',
props: {
disable: {
type: Boolean,
default: false
}
},
mounted () {
const keyNames = {
esc: ['Esc', 'Escape'],
tab: 'Tab',
enter: 'Enter',
space: [' ', 'Spacebar'],
up: ['Up', 'ArrowUp'],
left: ['Left', 'ArrowLeft'],
right: ['Right', 'ArrowRight'],
down: ['Down', 'ArrowDown'],
delete: ['Backspace', 'Delete', 'Del']
}
const listener = ($event) => {
if (this.disable) {
return
}
const keyName = Object.keys(keyNames).find(key => {
const keyName = $event.key
const value = keyNames[key]
return value === keyName || (Array.isArray(value) && value.includes(keyName))
})
if (keyName) {
// 避免和其他按键事件冲突
setTimeout(() => {
this.$emit(keyName, {})
}, 0)
}
}
document.addEventListener('keyup', listener)
this.$once('hook:beforeDestroy', () => {
document.removeEventListener('keyup', listener)
})
},
render: () => {}
}
// #endif
@@ -0,0 +1,380 @@
<template>
<view class="uni-data-tree">
<view class="uni-data-tree-input" @click="handleInput">
<slot :data="selectedPaths" :error="error">
<view class="input-value" :class="{'input-value-border': border}">
<text v-if="error!=null" class="error-text">{{error!.errMsg}}</text>
<scroll-view v-if="selectedPaths.length" class="selected-path" scroll-x="true">
<view class="selected-list">
<template v-for="(item, index) in selectedPaths">
<text class="text-color">{{item[mappingTextName]}}</text>
<text v-if="index<selectedPaths.length-1" class="input-split-line">{{split}}</text>
</template>
</view>
</scroll-view>
<text v-else-if="error==null&&!loading" class="placeholder">{{placeholder}}</text>
<view v-if="!readonly" class="arrow-area">
<view class="input-arrow"></view>
</view>
</view>
</slot>
<view v-if="loading && !isOpened" class="selected-loading">
<slot name="picker-loading" :loading="loading"></slot>
</view>
</view>
<view class="uni-data-tree-cover" v-if="isOpened" @click="handleClose"></view>
<view class="uni-data-tree-dialog" v-if="isOpened">
<view class="uni-popper__arrow"></view>
<view class="dialog-caption">
<view class="dialog-title-view">
<text class="dialog-title">{{popupTitle}}</text>
</view>
<view class="dialog-close" @click="handleClose">
<view class="dialog-close-plus" data-id="close"></view>
<view class="dialog-close-plus dialog-close-rotate" data-id="close"></view>
</view>
</view>
<view ref="pickerView" class="uni-data-pickerview">
<view v-if="error!=null" class="error">
<text class="error-text">{{error!.errMsg}}</text>
</view>
<scroll-view v-if="!isCloudDataList" :scroll-x="true">
<view class="selected-node-list">
<template v-for="(item, index) in selectedNodes">
<text class="selected-node-item" :class="{'selected-node-item-active':index==selectedIndex}"
@click="onTabSelect(index)">
{{item[mappingTextName]}}
</text>
</template>
</view>
</scroll-view>
<list-view class="list-view" :scroll-y="true">
<list-item class="list-item" v-for="(item, _) in currentDataList" @click="onNodeClick(item)">
<text class="item-text" :class="{'item-text-disabled': item['disable']}">{{item[mappingTextName]}}</text>
<text class="check" v-if="item[mappingValueName] == selectedNodes[selectedIndex][mappingValueName]"></text>
</list-item>
</list-view>
<view class="loading-cover" v-if="loading">
<slot name="pickerview-loading" :loading="loading"></slot>
</view>
</view>
</view>
</view>
</template>
<script>
import { dataPicker } from "../uni-data-pickerview/uni-data-picker.uts"
/**
* DataPicker 级联选择
* @description 支持单列、和多列级联选择。列数没有限制,如果屏幕显示不全,顶部tab区域会左右滚动。
* @tutorial https://ext.dcloud.net.cn/plugin?id=3796
* @property {String} popup-title 弹出窗口标题
* @property {Array} localdata 本地数据,参考
* @property {Boolean} border = [true|false] 是否有边框
* @property {Boolean} readonly = [true|false] 是否仅读
* @property {Boolean} preload = [true|false] 是否预加载数据
* @value true 开启预加载数据,点击弹出窗口后显示已加载数据
* @value false 关闭预加载数据,点击弹出窗口后开始加载数据
* @property {Boolean} step-searh = [true|false] 是否分布查询
* @value true 启用分布查询,仅查询当前选中节点
* @value false 关闭分布查询,一次查询出所有数据
* @property {String|DBFieldString} self-field 分布查询当前字段名称
* @property {String|DBFieldString} parent-field 分布查询父字段名称
* @property {String|DBCollectionString} collection 表名
* @property {String|DBFieldString} field 查询字段,多个字段用 `,` 分割
* @property {String} orderby 排序字段及正序倒叙设置
* @property {String|JQLString} where 查询条件
* @event {Function} popupshow 弹出的选择窗口打开时触发此事件
* @event {Function} popuphide 弹出的选择窗口关闭时触发此事件
*/
export default {
name: 'UniDataPicker',
emits: ['popupopened', 'popupclosed', 'nodeclick', 'change', 'input', 'update:modelValue', 'inputclick'],
mixins: [dataPicker],
props: {
popupTitle: {
type: String,
default: '请选择'
},
placeholder: {
type: String,
default: '请选择'
},
heightMobile: {
type: String,
default: ''
},
readonly: {
type: Boolean,
default: false
},
clearIcon: {
type: Boolean,
default: true
},
border: {
type: Boolean,
default: true
},
split: {
type: String,
default: '/'
},
ellipsis: {
type: Boolean,
default: true
}
},
data() {
return {
isOpened: false
}
},
computed: {
isShowClearIcon() : boolean {
if (this.readonly) {
return false
}
if (this.clearIcon && this.selectedPaths.length > 0) {
return true
}
return false
}
},
created() {
this.load()
},
methods: {
clear() {
},
load() {
if (this.isLocalData) {
this.loadLocalData()
} else if (this.isCloudDataList || this.isCloudDataTree) {
this.loadCloudDataPath()
}
},
show() {
this.isOpened = true
this.$emit('popupopened')
if (!this.hasCloudTreeData) {
this.loadData()
}
},
hide() {
this.isOpened = false
this.$emit('popupclosed')
},
handleInput() {
if (this.readonly) {
this.$emit('inputclick')
} else {
this.show()
}
},
handleClose() {
this.hide()
},
onFinish() {
this.selectedPaths = this.getChangeNodes()
this.$emit('change', this.selectedPaths)
this.hide()
}
}
}
</script>
<style>
@import url("../uni-data-pickerview/uni-data-pickerview.css");
.uni-data-tree {
position: relative;
}
.uni-data-tree-input {
position: relative;
}
.selected-loading {
display: flex;
justify-content: center;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
}
.error-text {
flex: 1;
font-size: 12px;
color: #DD524D;
}
.input-value {
flex-direction: row;
align-items: center;
flex-wrap: nowrap;
padding: 5px 5px;
padding-right: 5px;
overflow: hidden;
min-height: 28px;
}
.input-value-border {
border: 1px solid #e5e5e5;
border-radius: 5px;
}
.selected-path {
flex: 1;
flex-direction: row;
overflow: hidden;
}
.load-more {
width: 40px;
}
.selected-list {
flex-direction: row;
flex-wrap: nowrap;
}
.selected-item {
flex-direction: row;
flex-wrap: nowrap;
}
.text-color {
font-size: 14px;
color: #333;
}
.placeholder {
color: grey;
font-size: 14px;
}
.input-split-line {
opacity: .5;
margin-left: 1px;
margin-right: 1px;
}
.arrow-area {
position: relative;
padding: 0 12px;
margin-left: auto;
justify-content: center;
transform: rotate(-45deg);
transform-origin: center;
}
.input-arrow {
width: 8px;
height: 8px;
border-left: 2px solid #999;
border-bottom: 2px solid #999;
}
.uni-data-tree-cover {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, .4);
flex-direction: column;
z-index: 100;
}
.uni-data-tree-dialog {
position: fixed;
left: 0;
top: 20%;
right: 0;
bottom: 0;
background-color: #FFFFFF;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
flex-direction: column;
z-index: 102;
overflow: hidden;
}
.dialog-caption {
position: relative;
flex-direction: row;
}
.dialog-title-view {
flex: 1;
}
.dialog-title {
align-self: center;
padding: 0 10px;
line-height: 44px;
}
.dialog-close {
position: absolute;
top: 0;
right: 0;
bottom: 0;
flex-direction: row;
align-items: center;
padding: 0 15px;
}
.dialog-close-plus {
width: 16px;
height: 2px;
background-color: #666;
border-radius: 2px;
transform: rotate(45deg);
}
.dialog-close-rotate {
position: absolute;
transform: rotate(-45deg);
}
.uni-data-pickerview {
flex: 1;
}
.icon-clear {
display: flex;
align-items: center;
}
/* #ifdef H5 */
@media all and (min-width: 768px) {
.uni-data-tree-cover {
background-color: transparent;
}
.uni-data-tree-dialog {
position: absolute;
top: 55px;
height: auto;
min-height: 400px;
max-height: 50vh;
background-color: #fff;
border: 1px solid #EBEEF5;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
border-radius: 4px;
overflow: unset;
}
.dialog-caption {
display: none;
}
}
/* #endif */
</style>
@@ -0,0 +1,551 @@
<template>
<view class="uni-data-tree">
<view class="uni-data-tree-input" @click="handleInput">
<slot :options="options" :data="inputSelected" :error="errorMessage">
<view class="input-value" :class="{'input-value-border': border}">
<text v-if="errorMessage" class="selected-area error-text">{{errorMessage}}</text>
<view v-else-if="loading && !isOpened" class="selected-area">
<uni-load-more class="load-more" :contentText="loadMore" status="loading"></uni-load-more>
</view>
<scroll-view v-else-if="inputSelected.length" class="selected-area" scroll-x="true">
<view class="selected-list">
<view class="selected-item" v-for="(item,index) in inputSelected" :key="index">
<text class="text-color">{{item.text}}</text><text v-if="index<inputSelected.length-1"
class="input-split-line">{{split}}</text>
</view>
</view>
</scroll-view>
<text v-else class="selected-area placeholder">{{placeholder}}</text>
<view v-if="clearIcon && !readonly && inputSelected.length" class="icon-clear" @click.stop="clear">
<uni-icons type="clear" color="#c0c4cc" size="24"></uni-icons>
</view>
<view class="arrow-area" v-if="(!clearIcon || !inputSelected.length) && !readonly ">
<view class="input-arrow"></view>
</view>
</view>
</slot>
</view>
<view class="uni-data-tree-cover" v-if="isOpened" @click="handleClose"></view>
<view class="uni-data-tree-dialog" v-if="isOpened">
<view class="uni-popper__arrow"></view>
<view class="dialog-caption">
<view class="title-area">
<text class="dialog-title">{{popupTitle}}</text>
</view>
<view class="dialog-close" @click="handleClose">
<view class="dialog-close-plus" data-id="close"></view>
<view class="dialog-close-plus dialog-close-rotate" data-id="close"></view>
</view>
</view>
<data-picker-view class="picker-view" ref="pickerView" v-model="dataValue" :localdata="localdata"
:preload="preload" :collection="collection" :field="field" :orderby="orderby" :where="where"
:step-searh="stepSearh" :self-field="selfField" :parent-field="parentField" :managed-mode="true" :map="map"
:ellipsis="ellipsis" @change="onchange" @datachange="ondatachange" @nodeclick="onnodeclick">
</data-picker-view>
</view>
</view>
</template>
<script>
import dataPicker from "../uni-data-pickerview/uni-data-picker.js"
import DataPickerView from "../uni-data-pickerview/uni-data-pickerview.vue"
/**
* DataPicker 级联选择
* @description 支持单列、和多列级联选择。列数没有限制,如果屏幕显示不全,顶部tab区域会左右滚动。
* @tutorial https://ext.dcloud.net.cn/plugin?id=3796
* @property {String} popup-title 弹出窗口标题
* @property {Array} localdata 本地数据,参考
* @property {Boolean} border = [true|false] 是否有边框
* @property {Boolean} readonly = [true|false] 是否仅读
* @property {Boolean} preload = [true|false] 是否预加载数据
* @value true 开启预加载数据,点击弹出窗口后显示已加载数据
* @value false 关闭预加载数据,点击弹出窗口后开始加载数据
* @property {Boolean} step-searh = [true|false] 是否分布查询
* @value true 启用分布查询,仅查询当前选中节点
* @value false 关闭分布查询,一次查询出所有数据
* @property {String|DBFieldString} self-field 分布查询当前字段名称
* @property {String|DBFieldString} parent-field 分布查询父字段名称
* @property {String|DBCollectionString} collection 表名
* @property {String|DBFieldString} field 查询字段,多个字段用 `,` 分割
* @property {String} orderby 排序字段及正序倒叙设置
* @property {String|JQLString} where 查询条件
* @event {Function} popupshow 弹出的选择窗口打开时触发此事件
* @event {Function} popuphide 弹出的选择窗口关闭时触发此事件
*/
export default {
name: 'UniDataPicker',
emits: ['popupopened', 'popupclosed', 'nodeclick', 'input', 'change', 'update:modelValue','inputclick'],
mixins: [dataPicker],
components: {
DataPickerView
},
props: {
options: {
type: [Object, Array],
default () {
return {}
}
},
popupTitle: {
type: String,
default: '请选择'
},
placeholder: {
type: String,
default: '请选择'
},
heightMobile: {
type: String,
default: ''
},
readonly: {
type: Boolean,
default: false
},
clearIcon: {
type: Boolean,
default: true
},
border: {
type: Boolean,
default: true
},
split: {
type: String,
default: '/'
},
ellipsis: {
type: Boolean,
default: true
}
},
data() {
return {
isOpened: false,
inputSelected: []
}
},
created() {
this.$nextTick(() => {
this.load();
})
},
watch: {
localdata: {
handler() {
this.load()
},
deep: true
},
},
methods: {
clear() {
this._dispatchEvent([]);
},
onPropsChange() {
this._treeData = [];
this.selectedIndex = 0;
this.load();
},
load() {
if (this.readonly) {
this._processReadonly(this.localdata, this.dataValue);
return;
}
// 回显本地数据
if (this.isLocalData) {
this.loadData();
this.inputSelected = this.selected.slice(0);
} else if (this.isCloudDataList || this.isCloudDataTree) { // 回显 Cloud 数据
this.loading = true;
this.getCloudDataValue().then((res) => {
this.loading = false;
this.inputSelected = res;
}).catch((err) => {
this.loading = false;
this.errorMessage = err;
})
}
},
show() {
this.isOpened = true
setTimeout(() => {
this.$refs.pickerView.updateData({
treeData: this._treeData,
selected: this.selected,
selectedIndex: this.selectedIndex
})
}, 200)
this.$emit('popupopened')
},
hide() {
this.isOpened = false
this.$emit('popupclosed')
},
handleInput() {
if (this.readonly) {
this.$emit('inputclick')
return
}
this.show()
},
handleClose(e) {
this.hide()
},
onnodeclick(e) {
this.$emit('nodeclick', e)
},
ondatachange(e) {
this._treeData = this.$refs.pickerView._treeData
},
onchange(e) {
this.hide()
this.$nextTick(() => {
this.inputSelected = e;
})
this._dispatchEvent(e)
},
_processReadonly(dataList, value) {
var isTree = dataList.findIndex((item) => {
return item.children
})
if (isTree > -1) {
let inputValue
if (Array.isArray(value)) {
inputValue = value[value.length - 1]
if (typeof inputValue === 'object' && inputValue.value) {
inputValue = inputValue.value
}
} else {
inputValue = value
}
this.inputSelected = this._findNodePath(inputValue, this.localdata)
return
}
if (!this.hasValue) {
this.inputSelected = []
return
}
let result = []
for (let i = 0; i < value.length; i++) {
var val = value[i]
var item = dataList.find((v) => {
return v.value == val
})
if (item) {
result.push(item)
}
}
if (result.length) {
this.inputSelected = result
}
},
_filterForArray(data, valueArray) {
var result = []
for (let i = 0; i < valueArray.length; i++) {
var value = valueArray[i]
var found = data.find((item) => {
return item.value == value
})
if (found) {
result.push(found)
}
}
return result
},
_dispatchEvent(selected) {
let item = {}
if (selected.length) {
var value = new Array(selected.length)
for (var i = 0; i < selected.length; i++) {
value[i] = selected[i].value
}
item = selected[selected.length - 1]
} else {
item.value = ''
}
if (this.formItem) {
this.formItem.setValue(item.value)
}
this.$emit('input', item.value)
this.$emit('update:modelValue', item.value)
this.$emit('change', {
detail: {
value: selected
}
})
}
}
}
</script>
<style>
.uni-data-tree {
flex: 1;
position: relative;
font-size: 14px;
}
.error-text {
color: #DD524D;
}
.input-value {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
align-items: center;
flex-wrap: nowrap;
font-size: 14px;
/* line-height: 35px; */
padding: 0 10px;
padding-right: 5px;
overflow: hidden;
height: 35px;
/* #ifndef APP-NVUE */
box-sizing: border-box;
/* #endif */
}
.input-value-border {
border: 1px solid #e5e5e5;
border-radius: 5px;
}
.selected-area {
flex: 1;
overflow: hidden;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
}
.load-more {
/* #ifndef APP-NVUE */
margin-right: auto;
/* #endif */
/* #ifdef APP-NVUE */
width: 40px;
/* #endif */
}
.selected-list {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
flex-wrap: nowrap;
/* padding: 0 5px; */
}
.selected-item {
flex-direction: row;
/* padding: 0 1px; */
/* #ifndef APP-NVUE */
white-space: nowrap;
/* #endif */
}
.text-color {
color: #333;
}
.placeholder {
color: grey;
font-size: 12px;
}
.input-split-line {
opacity: .5;
}
.arrow-area {
position: relative;
width: 20px;
/* #ifndef APP-NVUE */
margin-bottom: 5px;
margin-left: auto;
display: flex;
/* #endif */
justify-content: center;
transform: rotate(-45deg);
transform-origin: center;
}
.input-arrow {
width: 7px;
height: 7px;
border-left: 1px solid #999;
border-bottom: 1px solid #999;
}
.uni-data-tree-cover {
position: fixed;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, .4);
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
z-index: 100;
}
.uni-data-tree-dialog {
position: fixed;
left: 0;
/* #ifndef APP-NVUE */
top: 20%;
/* #endif */
/* #ifdef APP-NVUE */
top: 200px;
/* #endif */
right: 0;
bottom: 0;
background-color: #FFFFFF;
border-top-left-radius: 10px;
border-top-right-radius: 10px;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
z-index: 102;
overflow: hidden;
/* #ifdef APP-NVUE */
width: 750rpx;
/* #endif */
}
.dialog-caption {
position: relative;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
/* border-bottom: 1px solid #f0f0f0; */
}
.title-area {
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
align-items: center;
/* #ifndef APP-NVUE */
margin: auto;
/* #endif */
padding: 0 10px;
}
.dialog-title {
/* font-weight: bold; */
line-height: 44px;
}
.dialog-close {
position: absolute;
top: 0;
right: 0;
bottom: 0;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
align-items: center;
padding: 0 15px;
}
.dialog-close-plus {
width: 16px;
height: 2px;
background-color: #666;
border-radius: 2px;
transform: rotate(45deg);
}
.dialog-close-rotate {
position: absolute;
transform: rotate(-45deg);
}
.picker-view {
flex: 1;
overflow: hidden;
}
.icon-clear {
display: flex;
align-items: center;
}
/* #ifdef H5 */
@media all and (min-width: 768px) {
.uni-data-tree-cover {
background-color: transparent;
}
.uni-data-tree-dialog {
position: absolute;
top: 55px;
height: auto;
min-height: 400px;
max-height: 50vh;
background-color: #fff;
border: 1px solid #EBEEF5;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
border-radius: 4px;
overflow: unset;
}
.dialog-caption {
display: none;
}
.icon-clear {
/* margin-right: 5px; */
}
}
/* #endif */
/* picker 弹出层通用的指示小三角, todo:扩展至上下左右方向定位 */
/* #ifndef APP-NVUE */
.uni-popper__arrow,
.uni-popper__arrow::after {
position: absolute;
display: block;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 6px;
}
.uni-popper__arrow {
filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
top: -6px;
left: 10%;
margin-right: 3px;
border-top-width: 0;
border-bottom-color: #EBEEF5;
}
.uni-popper__arrow::after {
content: " ";
top: 1px;
margin-left: -6px;
border-top-width: 0;
border-bottom-color: #fff;
}
/* #endif */
</style>
File diff suppressed because one or more lines are too long
@@ -0,0 +1,622 @@
export default {
props: {
localdata: {
type: [Array, Object],
default () {
return []
}
},
spaceInfo: {
type: Object,
default () {
return {}
}
},
collection: {
type: String,
default: ''
},
action: {
type: String,
default: ''
},
field: {
type: String,
default: ''
},
orderby: {
type: String,
default: ''
},
where: {
type: [String, Object],
default: ''
},
pageData: {
type: String,
default: 'add'
},
pageCurrent: {
type: Number,
default: 1
},
pageSize: {
type: Number,
default: 500
},
getcount: {
type: [Boolean, String],
default: false
},
getone: {
type: [Boolean, String],
default: false
},
gettree: {
type: [Boolean, String],
default: false
},
manual: {
type: Boolean,
default: false
},
value: {
type: [Array, String, Number],
default () {
return []
}
},
modelValue: {
type: [Array, String, Number],
default () {
return []
}
},
preload: {
type: Boolean,
default: false
},
stepSearh: {
type: Boolean,
default: true
},
selfField: {
type: String,
default: ''
},
parentField: {
type: String,
default: ''
},
multiple: {
type: Boolean,
default: false
},
map: {
type: Object,
default () {
return {
text: "text",
value: "value"
}
}
}
},
data() {
return {
loading: false,
errorMessage: '',
loadMore: {
contentdown: '',
contentrefresh: '',
contentnomore: ''
},
dataList: [],
selected: [],
selectedIndex: 0,
page: {
current: this.pageCurrent,
size: this.pageSize,
count: 0
}
}
},
computed: {
isLocalData() {
return !this.collection.length;
},
isCloudData() {
return this.collection.length > 0;
},
isCloudDataList() {
return (this.isCloudData && (!this.parentField && !this.selfField));
},
isCloudDataTree() {
return (this.isCloudData && this.parentField && this.selfField);
},
dataValue() {
let isModelValue = Array.isArray(this.modelValue) ? (this.modelValue.length > 0) : (this.modelValue !== null ||
this.modelValue !== undefined);
return isModelValue ? this.modelValue : this.value;
},
hasValue() {
if (typeof this.dataValue === 'number') {
return true
}
return (this.dataValue != null) && (this.dataValue.length > 0)
}
},
created() {
this.$watch(() => {
var al = [];
['pageCurrent',
'pageSize',
'spaceInfo',
'value',
'modelValue',
'localdata',
'collection',
'action',
'field',
'orderby',
'where',
'getont',
'getcount',
'gettree'
].forEach(key => {
al.push(this[key])
});
return al
}, (newValue, oldValue) => {
let needReset = false
for (let i = 2; i < newValue.length; i++) {
if (newValue[i] != oldValue[i]) {
needReset = true
break
}
}
if (newValue[0] != oldValue[0]) {
this.page.current = this.pageCurrent
}
this.page.size = this.pageSize
this.onPropsChange()
})
this._treeData = []
},
methods: {
onPropsChange() {
this._treeData = [];
},
// 填充 pickview 数据
async loadData() {
if (this.isLocalData) {
this.loadLocalData();
} else if (this.isCloudDataList) {
this.loadCloudDataList();
} else if (this.isCloudDataTree) {
this.loadCloudDataTree();
}
},
// 加载本地数据
async loadLocalData() {
this._treeData = [];
this._extractTree(this.localdata, this._treeData);
let inputValue = this.dataValue;
if (inputValue === undefined) {
return;
}
if (Array.isArray(inputValue)) {
inputValue = inputValue[inputValue.length - 1];
if (typeof inputValue === 'object' && inputValue[this.map.value]) {
inputValue = inputValue[this.map.value];
}
}
this.selected = this._findNodePath(inputValue, this.localdata);
},
// 加载 Cloud 数据 (单列)
async loadCloudDataList() {
if (this.loading) {
return;
}
this.loading = true;
try {
let response = await this.getCommand();
let responseData = response.result.data;
this._treeData = responseData;
this._updateBindData();
this._updateSelected();
this.onDataChange();
} catch (e) {
this.errorMessage = e;
} finally {
this.loading = false;
}
},
// 加载 Cloud 数据 (树形)
async loadCloudDataTree() {
if (this.loading) {
return;
}
this.loading = true;
try {
let commandOptions = {
field: this._cloudDataPostField(),
where: this._cloudDataTreeWhere()
};
if (this.gettree) {
commandOptions.startwith = `${this.selfField}=='${this.dataValue}'`;
}
let response = await this.getCommand(commandOptions);
let responseData = response.result.data;
this._treeData = responseData;
this._updateBindData();
this._updateSelected();
this.onDataChange();
} catch (e) {
this.errorMessage = e;
} finally {
this.loading = false;
}
},
// 加载 Cloud 数据 (节点)
async loadCloudDataNode(callback) {
if (this.loading) {
return;
}
this.loading = true;
try {
let commandOptions = {
field: this._cloudDataPostField(),
where: this._cloudDataNodeWhere()
};
let response = await this.getCommand(commandOptions);
let responseData = response.result.data;
callback(responseData);
} catch (e) {
this.errorMessage = e;
} finally {
this.loading = false;
}
},
// 回显 Cloud 数据
getCloudDataValue() {
if (this.isCloudDataList) {
return this.getCloudDataListValue();
}
if (this.isCloudDataTree) {
return this.getCloudDataTreeValue();
}
},
// 回显 Cloud 数据 (单列)
getCloudDataListValue() {
// 根据 field's as value标识匹配 where 条件
let where = [];
let whereField = this._getForeignKeyByField();
if (whereField) {
where.push(`${whereField} == '${this.dataValue}'`)
}
where = where.join(' || ');
if (this.where) {
where = `(${this.where}) && (${where})`
}
return this.getCommand({
field: this._cloudDataPostField(),
where
}).then((res) => {
this.selected = res.result.data;
return res.result.data;
});
},
// 回显 Cloud 数据 (树形)
getCloudDataTreeValue() {
return this.getCommand({
field: this._cloudDataPostField(),
getTreePath: {
startWith: `${this.selfField}=='${this.dataValue}'`
}
}).then((res) => {
let treePath = [];
this._extractTreePath(res.result.data, treePath);
this.selected = treePath;
return treePath;
});
},
getCommand(options = {}) {
/* eslint-disable no-undef */
let db = uniCloud.database(this.spaceInfo)
const action = options.action || this.action
if (action) {
db = db.action(action)
}
const collection = options.collection || this.collection
db = db.collection(collection)
const where = options.where || this.where
if (!(!where || !Object.keys(where).length)) {
db = db.where(where)
}
const field = options.field || this.field
if (field) {
db = db.field(field)
}
const orderby = options.orderby || this.orderby
if (orderby) {
db = db.orderBy(orderby)
}
const current = options.pageCurrent !== undefined ? options.pageCurrent : this.page.current
const size = options.pageSize !== undefined ? options.pageSize : this.page.size
const getCount = options.getcount !== undefined ? options.getcount : this.getcount
const getTree = options.gettree !== undefined ? options.gettree : this.gettree
const getOptions = {
getCount,
getTree
}
if (options.getTreePath) {
getOptions.getTreePath = options.getTreePath
}
db = db.skip(size * (current - 1)).limit(size).get(getOptions)
return db
},
_cloudDataPostField() {
let fields = [this.field];
if (this.parentField) {
fields.push(`${this.parentField} as parent_value`);
}
return fields.join(',');
},
_cloudDataTreeWhere() {
let result = []
let selected = this.selected
let parentField = this.parentField
if (parentField) {
result.push(`${parentField} == null || ${parentField} == ""`)
}
if (selected.length) {
for (var i = 0; i < selected.length - 1; i++) {
result.push(`${parentField} == '${selected[i].value}'`)
}
}
let where = []
if (this.where) {
where.push(`(${this.where})`)
}
if (result.length) {
where.push(`(${result.join(' || ')})`)
}
return where.join(' && ')
},
_cloudDataNodeWhere() {
let where = []
let selected = this.selected;
if (selected.length) {
where.push(`${this.parentField} == '${selected[selected.length - 1].value}'`);
}
where = where.join(' || ');
if (this.where) {
return `(${this.where}) && (${where})`
}
return where
},
_getWhereByForeignKey() {
let result = []
let whereField = this._getForeignKeyByField();
if (whereField) {
result.push(`${whereField} == '${this.dataValue}'`)
}
if (this.where) {
return `(${this.where}) && (${result.join(' || ')})`
}
return result.join(' || ')
},
_getForeignKeyByField() {
let fields = this.field.split(',');
let whereField = null;
for (let i = 0; i < fields.length; i++) {
const items = fields[i].split('as');
if (items.length < 2) {
continue;
}
if (items[1].trim() === 'value') {
whereField = items[0].trim();
break;
}
}
return whereField;
},
_updateBindData(node) {
const {
dataList,
hasNodes
} = this._filterData(this._treeData, this.selected)
let isleaf = this._stepSearh === false && !hasNodes
if (node) {
node.isleaf = isleaf
}
this.dataList = dataList
this.selectedIndex = dataList.length - 1
if (!isleaf && this.selected.length < dataList.length) {
this.selected.push({
value: null,
text: "请选择"
})
}
return {
isleaf,
hasNodes
}
},
_updateSelected() {
let dl = this.dataList
let sl = this.selected
let textField = this.map.text
let valueField = this.map.value
for (let i = 0; i < sl.length; i++) {
let value = sl[i].value
let dl2 = dl[i]
for (let j = 0; j < dl2.length; j++) {
let item2 = dl2[j]
if (item2[valueField] === value) {
sl[i].text = item2[textField]
break
}
}
}
},
_filterData(data, paths) {
let dataList = []
let hasNodes = true
dataList.push(data.filter((item) => {
return (item.parent_value === null || item.parent_value === undefined || item.parent_value === '')
}))
for (let i = 0; i < paths.length; i++) {
let value = paths[i].value
let nodes = data.filter((item) => {
return item.parent_value === value
})
if (nodes.length) {
dataList.push(nodes)
} else {
hasNodes = false
}
}
return {
dataList,
hasNodes
}
},
_extractTree(nodes, result, parent_value) {
let list = result || []
let valueField = this.map.value
for (let i = 0; i < nodes.length; i++) {
let node = nodes[i]
let child = {}
for (let key in node) {
if (key !== 'children') {
child[key] = node[key]
}
}
if (parent_value !== null && parent_value !== undefined && parent_value !== '') {
child.parent_value = parent_value
}
result.push(child)
let children = node.children
if (children) {
this._extractTree(children, result, node[valueField])
}
}
},
_extractTreePath(nodes, result) {
let list = result || []
for (let i = 0; i < nodes.length; i++) {
let node = nodes[i]
let child = {}
for (let key in node) {
if (key !== 'children') {
child[key] = node[key]
}
}
result.push(child)
let children = node.children
if (children) {
this._extractTreePath(children, result)
}
}
},
_findNodePath(key, nodes, path = []) {
let textField = this.map.text
let valueField = this.map.value
for (let i = 0; i < nodes.length; i++) {
let node = nodes[i]
let children = node.children
let text = node[textField]
let value = node[valueField]
path.push({
value,
text
})
if (value === key) {
return path
}
if (children) {
const p = this._findNodePath(key, children, path)
if (p.length) {
return p
}
}
path.pop()
}
return []
}
}
}
@@ -0,0 +1,693 @@
export type PaginationType = {
current : number,
size : number,
count : number
}
export type LoadMoreType = {
contentdown : string,
contentrefresh : string,
contentnomore : string
}
export type SelectedItemType = {
name : string,
value : string,
}
export type GetCommandOptions = {
collection ?: UTSJSONObject,
field ?: string,
orderby ?: string,
where ?: any,
pageData ?: string,
pageCurrent ?: number,
pageSize ?: number,
getCount ?: boolean,
getTree ?: any,
getTreePath ?: UTSJSONObject,
startwith ?: string,
limitlevel ?: number,
groupby ?: string,
groupField ?: string,
distinct ?: boolean,
pageIndistinct ?: boolean,
foreignKey ?: string,
loadtime ?: string,
manual ?: boolean
}
const DefaultSelectedNode = {
text: '请选择',
value: ''
}
export const dataPicker = defineMixin({
props: {
localdata: {
type: Array as PropType<Array<UTSJSONObject>>,
default: [] as Array<UTSJSONObject>
},
collection: {
type: Object,
default: ''
},
field: {
type: String,
default: ''
},
orderby: {
type: String,
default: ''
},
where: {
type: Object,
default: ''
},
pageData: {
type: String,
default: 'add'
},
pageCurrent: {
type: Number,
default: 1
},
pageSize: {
type: Number,
default: 20
},
getcount: {
type: Boolean,
default: false
},
gettree: {
type: Object,
default: ''
},
gettreepath: {
type: Object,
default: ''
},
startwith: {
type: String,
default: ''
},
limitlevel: {
type: Number,
default: 10
},
groupby: {
type: String,
default: ''
},
groupField: {
type: String,
default: ''
},
distinct: {
type: Boolean,
default: false
},
pageIndistinct: {
type: Boolean,
default: false
},
foreignKey: {
type: String,
default: ''
},
loadtime: {
type: String,
default: 'auto'
},
manual: {
type: Boolean,
default: false
},
preload: {
type: Boolean,
default: false
},
stepSearh: {
type: Boolean,
default: true
},
selfField: {
type: String,
default: ''
},
parentField: {
type: String,
default: ''
},
multiple: {
type: Boolean,
default: false
},
value: {
type: Object,
default: ''
},
modelValue: {
type: Object,
default: ''
},
defaultProps: {
type: Object as PropType<UTSJSONObject>,
}
},
data() {
return {
loading: false,
error: null as UniCloudError | null,
treeData: [] as Array<UTSJSONObject>,
selectedIndex: 0,
selectedNodes: [] as Array<UTSJSONObject>,
selectedPages: [] as Array<UTSJSONObject>[],
selectedValue: '',
selectedPaths: [] as Array<UTSJSONObject>,
pagination: {
current: 1,
size: 20,
count: 0
} as PaginationType
}
},
computed: {
mappingTextName() : string {
// TODO
return (this.defaultProps != null) ? this.defaultProps!.getString('text', 'text') : 'text'
},
mappingValueName() : string {
// TODO
return (this.defaultProps != null) ? this.defaultProps!.getString('value', 'value') : 'value'
},
currentDataList() : Array<UTSJSONObject> {
if (this.selectedIndex > this.selectedPages.length - 1) {
return [] as Array<UTSJSONObject>
}
return this.selectedPages[this.selectedIndex]
},
isLocalData() : boolean {
return this.localdata.length > 0
},
isCloudData() : boolean {
return this._checkIsNotNull(this.collection)
},
isCloudDataList() : boolean {
return (this.isCloudData && (this.parentField.length == 0 && this.selfField.length == 0))
},
isCloudDataTree() : boolean {
return (this.isCloudData && this.parentField.length > 0 && this.selfField.length > 0)
},
dataValue() : any {
return this.hasModelValue ? this.modelValue : this.value
},
hasCloudTreeData() : boolean {
return this.treeData.length > 0
},
hasModelValue() : boolean {
if (typeof this.modelValue == 'string') {
const valueString = this.modelValue as string
return (valueString.length > 0)
} else if (Array.isArray(this.modelValue)) {
const valueArray = this.modelValue as Array<string>
return (valueArray.length > 0)
}
return false
},
hasCloudDataValue() : boolean {
if (typeof this.dataValue == 'string') {
const valueString = this.dataValue as string
return (valueString.length > 0)
}
return false
}
},
created() {
this.pagination.current = this.pageCurrent
this.pagination.size = this.pageSize
this.$watch(
() : any => [
this.pageCurrent,
this.pageSize,
this.localdata,
this.value,
this.collection,
this.field,
this.getcount,
this.orderby,
this.where,
this.groupby,
this.groupField,
this.distinct
],
(newValue : Array<any>, oldValue : Array<any>) => {
this.pagination.size = this.pageSize
if (newValue[0] !== oldValue[0]) {
this.pagination.current = this.pageCurrent
}
this.onPropsChange()
}
)
},
methods: {
onPropsChange() {
this.selectedIndex = 0
this.treeData.length = 0
this.selectedNodes.length = 0
this.selectedPages.length = 0
this.selectedPaths.length = 0
// 加载数据
this.$nextTick(() => {
this.loadData()
})
},
onTabSelect(index : number) {
this.selectedIndex = index
},
onNodeClick(nodeData : UTSJSONObject) {
if (nodeData.getBoolean('disable', false)) {
return
}
const isLeaf = this._checkIsLeafNode(nodeData)
this._trimSelectedNodes(nodeData)
this.$emit('nodeclick', nodeData)
if (this.isLocalData) {
if (isLeaf || !this._checkHasChildren(nodeData)) {
this.onFinish()
}
} else if (this.isCloudDataList) {
this.onFinish()
} else if (this.isCloudDataTree) {
if (isLeaf) {
this.onFinish()
} else if (!this._checkHasChildren(nodeData)) {
// 尝试请求一次,如果没有返回数据标记为叶子节点
this.loadCloudDataNode(nodeData)
}
}
},
getChangeNodes(): Array<UTSJSONObject> {
const nodes: Array<UTSJSONObject> = []
this.selectedNodes.forEach((node : UTSJSONObject) => {
const newNode: UTSJSONObject = {}
newNode[this.mappingTextName] = node.getString(this.mappingTextName)
newNode[this.mappingValueName] = node.getString(this.mappingValueName)
nodes.push(newNode)
})
return nodes
},
onFinish() { },
// 加载数据(自动判定环境)
loadData() {
if (this.isLocalData) {
this.loadLocalData()
} else if (this.isCloudDataList) {
this.loadCloudDataList()
} else if (this.isCloudDataTree) {
this.loadCloudDataTree()
}
},
// 加载本地数据
loadLocalData() {
this.treeData = this.localdata
if (Array.isArray(this.dataValue)) {
const value = this.dataValue as Array<UTSJSONObject>
this.selectedPaths = value.slice(0)
this._pushSelectedTreeNodes(value, this.localdata)
} else {
this._pushSelectedNodes(this.localdata)
}
},
// 加载 Cloud 数据 (单列)
loadCloudDataList() {
this._loadCloudData(null, (data : Array<UTSJSONObject>) => {
this.treeData = data
this._pushSelectedNodes(data)
})
},
// 加载 Cloud 数据 (树形)
loadCloudDataTree() {
let commandOptions = {
field: this._cloudDataPostField(),
where: this._cloudDataTreeWhere(),
getTree: true
} as GetCommandOptions
if (this._checkIsNotNull(this.gettree)) {
commandOptions.startwith = `${this.selfField}=='${this.dataValue as string}'`
}
this._loadCloudData(commandOptions, (data : Array<UTSJSONObject>) => {
this.treeData = data
if (this.selectedPaths.length > 0) {
this._pushSelectedTreeNodes(this.selectedPaths, data)
} else {
this._pushSelectedNodes(data)
}
})
},
// 加载 Cloud 数据 (节点)
loadCloudDataNode(nodeData : UTSJSONObject) {
const commandOptions = {
field: this._cloudDataPostField(),
where: this._cloudDataNodeWhere()
} as GetCommandOptions
this._loadCloudData(commandOptions, (data : Array<UTSJSONObject>) => {
nodeData['children'] = data
if (data.length == 0) {
nodeData['isleaf'] = true
this.onFinish()
} else {
this._pushSelectedNodes(data)
}
})
},
// 回显 Cloud Tree Path
loadCloudDataPath() {
if (!this.hasCloudDataValue) {
return
}
const command : GetCommandOptions = {}
// 单列
if (this.isCloudDataList) {
// 根据 field's as value标识匹配 where 条件
let where : Array<string> = [];
let whereField = this._getForeignKeyByField();
if (whereField.length > 0) {
where.push(`${whereField} == '${this.dataValue as string}'`)
}
let whereString = where.join(' || ')
if (this._checkIsNotNull(this.where)) {
whereString = `(${this.where}) && (${whereString})`
}
command.field = this._cloudDataPostField()
command.where = whereString
}
// 树形
if (this.isCloudDataTree) {
command.field = this._cloudDataPostField()
command.getTreePath = {
startWith: `${this.selfField}=='${this.dataValue as string}'`
}
}
this._loadCloudData(command, (data : Array<UTSJSONObject>) => {
this._extractTreePath(data, this.selectedPaths)
})
},
_loadCloudData(options ?: GetCommandOptions, callback ?: ((data : Array<UTSJSONObject>) => void)) {
if (this.loading) {
return
}
this.loading = true
this.error = null
this._getCommand(options).then((response : UniCloudDBGetResult) => {
callback?.(response.data)
}).catch((err : any | null) => {
this.error = err as UniCloudError
}).finally(() => {
this.loading = false
})
},
_cloudDataPostField() : string {
let fields = [this.field];
if (this.parentField.length > 0) {
fields.push(`${this.parentField} as parent_value`)
}
return fields.join(',')
},
_cloudDataTreeWhere() : string {
let result : Array<string> = []
let selectedNodes = this.selectedNodes.length > 0 ? this.selectedNodes : this.selectedPaths
let parentField = this.parentField
if (parentField.length > 0) {
result.push(`${parentField} == null || ${parentField} == ""`)
}
if (selectedNodes.length > 0) {
for (var i = 0; i < selectedNodes.length - 1; i++) {
const parentFieldValue = selectedNodes[i].getString('value', '')
result.push(`${parentField} == '${parentFieldValue}'`)
}
}
let where : Array<string> = []
if (this._checkIsNotNull(this.where)) {
where.push(`(${this.where as string})`)
}
if (result.length > 0) {
where.push(`(${result.join(' || ')})`)
}
return where.join(' && ')
},
_cloudDataNodeWhere() : string {
const where : Array<string> = []
if (this.selectedNodes.length > 0) {
const value = this.selectedNodes[this.selectedNodes.length - 1].getString('value', '')
where.push(`${this.parentField} == '${value}'`)
}
let whereString = where.join(' || ')
if (this._checkIsNotNull(this.where)) {
return `(${this.where as string}) && (${whereString})`
}
return whereString
},
_getWhereByForeignKey() : string {
let result : Array<string> = []
let whereField = this._getForeignKeyByField();
if (whereField.length > 0) {
result.push(`${whereField} == '${this.dataValue as string}'`)
}
if (this._checkIsNotNull(this.where)) {
return `(${this.where}) && (${result.join(' || ')})`
}
return result.join(' || ')
},
_getForeignKeyByField() : string {
const fields = this.field.split(',')
let whereField = ''
for (let i = 0; i < fields.length; i++) {
const items = fields[i].split('as')
if (items.length < 2) {
continue
}
if (items[1].trim() === 'value') {
whereField = items[0].trim()
break
}
}
return whereField
},
_getCommand(options ?: GetCommandOptions) : Promise<UniCloudDBGetResult> {
let db = uniCloud.databaseForJQL()
let collection = Array.isArray(this.collection) ? db.collection(...(this.collection as Array<any>)) : db.collection(this.collection)
let filter : UniCloudDBFilter | null = null
if (this.foreignKey.length > 0) {
filter = collection.foreignKey(this.foreignKey)
}
const where : any = options?.where ?? this.where
if (typeof where == 'string') {
const whereString = where as string
if (whereString.length > 0) {
filter = (filter != null) ? filter.where(where) : collection.where(where)
}
} else {
filter = (filter != null) ? filter.where(where) : collection.where(where)
}
let query : UniCloudDBQuery | null = null
if (this.field.length > 0) {
query = (filter != null) ? filter.field(this.field) : collection.field(this.field)
}
if (this.groupby.length > 0) {
if (query != null) {
query = query.groupBy(this.groupby)
} else if (filter != null) {
query = filter.groupBy(this.groupby)
}
}
if (this.groupField.length > 0) {
if (query != null) {
query = query.groupField(this.groupField)
} else if (filter != null) {
query = filter.groupField(this.groupField)
}
}
if (this.distinct == true) {
if (query != null) {
query = query.distinct(this.field)
} else if (filter != null) {
query = filter.distinct(this.field)
}
}
if (this.orderby.length > 0) {
if (query != null) {
query = query.orderBy(this.orderby)
} else if (filter != null) {
query = filter.orderBy(this.orderby)
}
}
const size = this.pagination.size
const current = this.pagination.current
if (query != null) {
query = query.skip(size * (current - 1)).limit(size)
} else if (filter != null) {
query = filter.skip(size * (current - 1)).limit(size)
} else {
query = collection.skip(size * (current - 1)).limit(size)
}
const getOptions = {}
const treeOptions = {
limitLevel: this.limitlevel,
startWith: this.startwith
}
if (this.getcount == true) {
getOptions['getCount'] = this.getcount
}
const getTree : any = options?.getTree ?? this.gettree
if (typeof getTree == 'string') {
const getTreeString = getTree as string
if (getTreeString.length > 0) {
getOptions['getTree'] = treeOptions
}
} else if (typeof getTree == 'object') {
getOptions['getTree'] = treeOptions
} else {
getOptions['getTree'] = getTree
}
const getTreePath = options?.getTreePath ?? this.gettreepath
if (typeof getTreePath == 'string') {
const getTreePathString = getTreePath as string
if (getTreePathString.length > 0) {
getOptions['getTreePath'] = getTreePath
}
} else {
getOptions['getTreePath'] = getTreePath
}
return query.get(getOptions)
},
_checkIsNotNull(value : any) : boolean {
if (typeof value == 'string') {
const valueString = value as string
return (valueString.length > 0)
} else if (value instanceof UTSJSONObject) {
return true
}
return false
},
_checkIsLeafNode(nodeData : UTSJSONObject) : boolean {
if (this.selectedIndex >= this.limitlevel) {
return true
}
if (nodeData.getBoolean('isleaf', false)) {
return true
}
return false
},
_checkHasChildren(nodeData : UTSJSONObject) : boolean {
const children = nodeData.getArray('children') ?? ([] as Array<any>)
return children.length > 0
},
_pushSelectedNodes(nodes : Array<UTSJSONObject>) {
this.selectedNodes.push(DefaultSelectedNode)
this.selectedPages.push(nodes)
this.selectedIndex = this.selectedPages.length - 1
},
_trimSelectedNodes(nodeData : UTSJSONObject) {
this.selectedNodes.splice(this.selectedIndex)
this.selectedNodes.push(nodeData)
if (this.selectedPages.length > 0) {
this.selectedPages.splice(this.selectedIndex + 1)
}
const children = nodeData.getArray<UTSJSONObject>('children') ?? ([] as Array<UTSJSONObject>)
if (children.length > 0) {
this.selectedNodes.push(DefaultSelectedNode)
this.selectedPages.push(children)
}
this.selectedIndex = this.selectedPages.length - 1
},
_pushSelectedTreeNodes(paths : Array<UTSJSONObject>, nodes : Array<UTSJSONObject>) {
let children : Array<UTSJSONObject> = nodes
paths.forEach((node : UTSJSONObject) => {
const findNode = children.find((item : UTSJSONObject) : boolean => {
return (item.getString(this.mappingValueName) == node.getString(this.mappingValueName))
})
if (findNode != null) {
this.selectedPages.push(children)
this.selectedNodes.push(node)
children = findNode.getArray<UTSJSONObject>('children') ?? ([] as Array<UTSJSONObject>)
}
})
this.selectedIndex = this.selectedPages.length - 1
},
_extractTreePath(nodes : Array<UTSJSONObject>, result : Array<UTSJSONObject>) {
if (nodes.length == 0) {
return
}
const node = nodes[0]
result.push(node)
const children = node.getArray<UTSJSONObject>('children')
if (Array.isArray(children) && children!.length > 0) {
this._extractTreePath(children, result)
}
}
}
})
@@ -0,0 +1,76 @@
.uni-data-pickerview {
position: relative;
flex-direction: column;
overflow: hidden;
}
.loading-cover {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
align-items: center;
justify-content: center;
background-color: rgba(150, 150, 150, .1);
}
.error {
background-color: #fff;
padding: 15px;
}
.error-text {
color: #DD524D;
}
.selected-node-list {
flex-direction: row;
flex-wrap: nowrap;
}
.selected-node-item {
margin-left: 10px;
margin-right: 10px;
padding: 8px 10px 8px 10px;
border-bottom: 2px solid transparent;
}
.selected-node-item-active {
color: #007aff;
border-bottom-color: #007aff;
}
.list-view {
flex: 1;
}
.list-item {
flex-direction: row;
justify-content: space-between;
padding: 12px 15px;
border-bottom: 1px solid #f0f0f0;
}
.item-text {
color: #333333;
}
.item-text-disabled {
opacity: .5;
}
.item-text-overflow {
overflow: hidden;
}
.check {
margin-right: 5px;
border: 2px solid #007aff;
border-left: 0;
border-top: 0;
height: 12px;
width: 6px;
transform-origin: center;
transform: rotate(45deg);
}
@@ -0,0 +1,69 @@
<template>
<view class="uni-data-pickerview">
<view v-if="error!=null" class="error">
<text class="error-text">{{error!.errMsg}}</text>
</view>
<scroll-view v-if="!isCloudDataList" :scroll-x="true">
<view class="selected-node-list">
<template v-for="(item, index) in selectedNodes">
<text class="selected-node-item" :class="{'selected-node-item-active':index==selectedIndex}"
@click="onTabSelect(index)">
{{item[mappingTextName]}}
</text>
</template>
</view>
</scroll-view>
<list-view class="list-view" :scroll-y="true">
<list-item class="list-item" v-for="(item, _) in currentDataList" @click="onNodeClick(item)">
<text class="item-text" :class="{'item-text-disabled': item['disable']}">{{item[mappingTextName]}}</text>
<text class="check" v-if="item[mappingValueName] == selectedNodes[selectedIndex][mappingValueName]"></text>
</list-item>
</list-view>
<view class="loading-cover" v-if="loading">
<slot name="pickerview-loading" :loading="loading"></slot>
</view>
</view>
</template>
<script>
import { dataPicker } from "./uni-data-picker.uts"
/**
* DataPickerview
* @description uni-data-pickerview
* @tutorial https://ext.dcloud.net.cn/plugin?id=3796
* @property {Array} localdata 本地数据,参考
* @property {Boolean} step-searh = [true|false] 是否分布查询
* @value true 启用分布查询,仅查询当前选中节点
* @value false 关闭分布查询,一次查询出所有数据
* @property {String|DBFieldString} self-field 分布查询当前字段名称
* @property {String|DBFieldString} parent-field 分布查询父字段名称
* @property {String|DBCollectionString} collection 表名
* @property {String|DBFieldString} field 查询字段,多个字段用 `,` 分割
* @property {String} orderby 排序字段及正序倒叙设置
* @property {String|JQLString} where 查询条件
*/
export default {
name: 'UniDataPickerView',
emits: ['nodeclick', 'change', 'update:modelValue'],
mixins: [dataPicker],
props: {
ellipsis: {
type: Boolean,
default: true
}
},
created() {
this.loadData()
},
methods: {
onFinish() {
this.$emit('change', this.getChangeNodes())
}
}
}
</script>
<style>
@import url("uni-data-pickerview.css");
</style>
@@ -0,0 +1,323 @@
<template>
<view class="uni-data-pickerview">
<scroll-view v-if="!isCloudDataList" class="selected-area" scroll-x="true">
<view class="selected-list">
<view
class="selected-item"
v-for="(item,index) in selected"
:key="index"
:class="{
'selected-item-active':index == selectedIndex
}"
@click="handleSelect(index)"
>
<text>{{item.text || ''}}</text>
</view>
</view>
</scroll-view>
<view class="tab-c">
<scroll-view class="list" :scroll-y="true">
<view class="item" :class="{'is-disabled': !!item.disable}" v-for="(item, j) in dataList[selectedIndex]" :key="j"
@click="handleNodeClick(item, selectedIndex, j)">
<text class="item-text">{{item[map.text]}}</text>
<view class="check" v-if="selected.length > selectedIndex && item[map.value] == selected[selectedIndex].value"></view>
</view>
</scroll-view>
<view class="loading-cover" v-if="loading">
<uni-load-more class="load-more" :contentText="loadMore" status="loading"></uni-load-more>
</view>
<view class="error-message" v-if="errorMessage">
<text class="error-text">{{errorMessage}}</text>
</view>
</view>
</view>
</template>
<script>
import dataPicker from "./uni-data-picker.js"
/**
* DataPickerview
* @description uni-data-pickerview
* @tutorial https://ext.dcloud.net.cn/plugin?id=3796
* @property {Array} localdata 本地数据,参考
* @property {Boolean} step-searh = [true|false] 是否分布查询
* @value true 启用分布查询,仅查询当前选中节点
* @value false 关闭分布查询,一次查询出所有数据
* @property {String|DBFieldString} self-field 分布查询当前字段名称
* @property {String|DBFieldString} parent-field 分布查询父字段名称
* @property {String|DBCollectionString} collection 表名
* @property {String|DBFieldString} field 查询字段,多个字段用 `,` 分割
* @property {String} orderby 排序字段及正序倒叙设置
* @property {String|JQLString} where 查询条件
*/
export default {
name: 'UniDataPickerView',
emits: ['nodeclick', 'change', 'datachange', 'update:modelValue'],
mixins: [dataPicker],
props: {
managedMode: {
type: Boolean,
default: false
},
ellipsis: {
type: Boolean,
default: true
}
},
created() {
if (!this.managedMode) {
this.$nextTick(() => {
this.loadData();
})
}
},
methods: {
onPropsChange() {
this._treeData = [];
this.selectedIndex = 0;
this.$nextTick(() => {
this.loadData();
})
},
handleSelect(index) {
this.selectedIndex = index;
},
handleNodeClick(item, i, j) {
if (item.disable) {
return;
}
const node = this.dataList[i][j];
const text = node[this.map.text];
const value = node[this.map.value];
if (i < this.selected.length - 1) {
this.selected.splice(i, this.selected.length - i)
this.selected.push({
text,
value
})
} else if (i === this.selected.length - 1) {
this.selected.splice(i, 1, {
text,
value
})
}
if (node.isleaf) {
this.onSelectedChange(node, node.isleaf)
return
}
const {
isleaf,
hasNodes
} = this._updateBindData()
// 本地数据
if (this.isLocalData) {
this.onSelectedChange(node, (!hasNodes || isleaf))
} else if (this.isCloudDataList) { // Cloud 数据 (单列)
this.onSelectedChange(node, true)
} else if (this.isCloudDataTree) { // Cloud 数据 (树形)
if (isleaf) {
this.onSelectedChange(node, node.isleaf)
} else if (!hasNodes) { // 请求一次服务器以确定是否为叶子节点
this.loadCloudDataNode((data) => {
if (!data.length) {
node.isleaf = true
} else {
this._treeData.push(...data)
this._updateBindData(node)
}
this.onSelectedChange(node, node.isleaf)
})
}
}
},
updateData(data) {
this._treeData = data.treeData
this.selected = data.selected
if (!this._treeData.length) {
this.loadData()
} else {
//this.selected = data.selected
this._updateBindData()
}
},
onDataChange() {
this.$emit('datachange');
},
onSelectedChange(node, isleaf) {
if (isleaf) {
this._dispatchEvent()
}
if (node) {
this.$emit('nodeclick', node)
}
},
_dispatchEvent() {
this.$emit('change', this.selected.slice(0))
}
}
}
</script>
<style lang="scss">
$uni-primary: #007aff !default;
.uni-data-pickerview {
flex: 1;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
overflow: hidden;
height: 100%;
}
.error-text {
color: #DD524D;
}
.loading-cover {
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
background-color: rgba(255, 255, 255, .5);
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: column;
align-items: center;
z-index: 1001;
}
.load-more {
/* #ifndef APP-NVUE */
margin: auto;
/* #endif */
}
.error-message {
background-color: #fff;
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
padding: 15px;
opacity: .9;
z-index: 102;
}
/* #ifdef APP-NVUE */
.selected-area {
width: 750rpx;
}
/* #endif */
.selected-list {
/* #ifndef APP-NVUE */
display: flex;
flex-wrap: nowrap;
/* #endif */
flex-direction: row;
padding: 0 5px;
border-bottom: 1px solid #f8f8f8;
}
.selected-item {
margin-left: 10px;
margin-right: 10px;
padding: 12px 0;
text-align: center;
/* #ifndef APP-NVUE */
white-space: nowrap;
/* #endif */
}
.selected-item-text-overflow {
width: 168px;
/* fix nvue */
overflow: hidden;
/* #ifndef APP-NVUE */
width: 6em;
white-space: nowrap;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
/* #endif */
}
.selected-item-active {
border-bottom: 2px solid $uni-primary;
}
.selected-item-text {
color: $uni-primary;
}
.tab-c {
position: relative;
flex: 1;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
overflow: hidden;
}
.list {
flex: 1;
}
.item {
padding: 12px 15px;
/* border-bottom: 1px solid #f0f0f0; */
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex-direction: row;
justify-content: space-between;
}
.is-disabled {
opacity: .5;
}
.item-text {
/* flex: 1; */
color: #333333;
}
.item-text-overflow {
width: 280px;
/* fix nvue */
overflow: hidden;
/* #ifndef APP-NVUE */
width: 20em;
white-space: nowrap;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
/* #endif */
}
.check {
margin-right: 5px;
border: 2px solid $uni-primary;
border-left: 0;
border-top: 0;
height: 12px;
width: 6px;
transform-origin: center;
/* #ifndef APP-NVUE */
transition: all 0.3s;
/* #endif */
transform: rotate(45deg);
}
</style>
@@ -0,0 +1,91 @@
{
"id": "uni-data-picker",
"displayName": "uni-data-picker 数据驱动的picker选择器",
"version": "2.0.0",
"description": "单列、多列级联选择器,常用于省市区城市选择、公司部门选择、多级分类等场景",
"keywords": [
"uni-ui",
"uniui",
"picker",
"级联",
"省市区",
""
],
"repository": "https://github.com/dcloudio/uni-ui",
"engines": {
"HBuilderX": ""
},
"directories": {
"example": "../../temps/example_temps"
},
"dcloudext": {
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "https://www.npmjs.com/package/@dcloudio/uni-ui",
"type": "component-vue"
},
"uni_modules": {
"dependencies": [
"uni-load-more",
"uni-icons",
"uni-scss"
],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y"
},
"client": {
"App": {
"app-vue": "y",
"app-nvue": "y",
"app-uvue": "y"
},
"H5-mobile": {
"Safari": "y",
"Android Browser": "y",
"微信浏览器(Android)": "y",
"QQ浏览器(Android)": "y"
},
"H5-pc": {
"Chrome": "y",
"IE": "y",
"Edge": "y",
"Firefox": "y",
"Safari": "y"
},
"小程序": {
"微信": "y",
"阿里": "y",
"百度": "y",
"字节跳动": "y",
"QQ": "y",
"京东": "u"
},
"快应用": {
"华为": "u",
"联盟": "u"
},
"Vue": {
"vue2": "y",
"vue3": "y"
}
}
}
}
}
@@ -0,0 +1,22 @@
## DataPicker 级联选择
> **组件名:uni-data-picker**
> 代码块: `uDataPicker`
> 关联组件:`uni-data-pickerview`、`uni-load-more`。
`<uni-data-picker>` 是一个选择类[datacom组件](https://uniapp.dcloud.net.cn/component/datacom)。
支持单列、和多列级联选择。列数没有限制,如果屏幕显示不全,顶部tab区域会左右滚动。
候选数据支持一次性加载完毕,也支持懒加载,比如示例图中,选择了“北京”后,动态加载北京的区县数据。
`<uni-data-picker>` 组件尤其适用于地址选择、分类选择等选择类。
`<uni-data-picker>` 支持本地数据、云端静态数据(json),uniCloud云数据库数据。
`<uni-data-picker>` 可以通过JQL直连uniCloud云数据库,配套[DB Schema](https://uniapp.dcloud.net.cn/uniCloud/schema),可在schema2code中自动生成前端页面,还支持服务器端校验。
在uniCloud数据表中新建表“uni-id-address”和“opendb-city-china”,这2个表的schema自带foreignKey关联。在“uni-id-address”表的表结构页面使用schema2code生成前端页面,会自动生成地址管理的维护页面,自动从“opendb-city-china”表包含的中国所有省市区信息里选择地址。
### [查看文档](https://uniapp.dcloud.io/component/uniui/uni-data-picker)
#### 如使用过程中有任何问题,或者您对uni-ui有一些好的建议,欢迎加入 uni-ui 交流群:871950839
@@ -0,0 +1,39 @@
## 1.0.8(2024-03-28)
- 修复 在vue2下:style动态绑定导致编译失败的bug
## 1.0.7(2024-01-20)
- 修复 长文本回显超过容器的bug,超过容器部分显示省略号
## 1.0.6(2023-04-12)
- 修复 微信小程序点击时会改变背景颜色的 bug
## 1.0.5(2023-02-03)
- 修复 禁用时会显示清空按钮
## 1.0.4(2023-02-02)
- 优化 查询条件短期内多次变更只查询最后一次变更后的结果
- 调整 内部缓存键名调整为 uni-data-select-lastSelectedValue
## 1.0.3(2023-01-16)
- 修复 不关联服务空间报错的问题
## 1.0.2(2023-01-14)
- 新增 属性 `format` 可用于格式化显示选项内容
## 1.0.1(2022-12-06)
- 修复 当where变化时,数据不会自动更新的问题
## 0.1.9(2022-09-05)
- 修复 微信小程序下拉框出现后选择会点击到蒙板后面的输入框
## 0.1.8(2022-08-29)
- 修复 点击的位置不准确
## 0.1.7(2022-08-12)
- 新增 支持 disabled 属性
## 0.1.6(2022-07-06)
- 修复 pc端宽度异常的bug
## 0.1.5
- 修复 pc端宽度异常的bug
## 0.1.4(2022-07-05)
- 优化 显示样式
## 0.1.3(2022-06-02)
- 修复 localdata 赋值不生效的 bug
- 新增 支持 uni.scss 修改颜色
- 新增 支持选项禁用(数据选项设置 disabled: true 即禁用)
## 0.1.2(2022-05-08)
- 修复 当 value 为 0 时选择不生效的 bug
## 0.1.1(2022-05-07)
- 新增 记住上次的选项(仅 collection 存在时有效)
## 0.1.0(2022-04-22)
- 初始化
@@ -0,0 +1,562 @@
<template>
<view class="uni-stat__select">
<span v-if="label" class="uni-label-text hide-on-phone">{{label + ':'}}</span>
<view class="uni-stat-box" :class="{'uni-stat__actived': current}">
<view class="uni-select" :class="{'uni-select--disabled':disabled}">
<view class="uni-select__input-box" @click="toggleSelector">
<view v-if="current" class="uni-select__input-text">{{textShow}}</view>
<view v-else class="uni-select__input-text uni-select__input-placeholder">{{typePlaceholder}}</view>
<view v-if="current && clear && !disabled" @click.stop="clearVal">
<uni-icons type="clear" color="#c0c4cc" size="24" />
</view>
<view v-else>
<uni-icons :type="showSelector? 'top' : 'bottom'" size="14" color="#999" />
</view>
</view>
<view class="uni-select--mask" v-if="showSelector" @click="toggleSelector" />
<view class="uni-select__selector" :style="getOffsetByPlacement" v-if="showSelector">
<view :class="placement=='bottom'?'uni-popper__arrow_bottom':'uni-popper__arrow_top'"></view>
<scroll-view scroll-y="true" class="uni-select__selector-scroll">
<view class="uni-select__selector-empty" v-if="mixinDatacomResData.length === 0">
<text>{{emptyTips}}</text>
</view>
<view v-else class="uni-select__selector-item" v-for="(item,index) in mixinDatacomResData" :key="index"
@click="change(item)">
<text :class="{'uni-select__selector__disabled': item.disable}">{{formatItemName(item)}}</text>
</view>
</scroll-view>
</view>
</view>
</view>
</view>
</template>
<script>
/**
* DataChecklist 数据选择器
* @description 通过数据渲染的下拉框组件
* @tutorial https://uniapp.dcloud.io/component/uniui/uni-data-select
* @property {String} value 默认值
* @property {Array} localdata 本地数据 ,格式 [{text:'',value:''}]
* @property {Boolean} clear 是否可以清空已选项
* @property {Boolean} emptyText 没有数据时显示的文字 ,本地数据无效
* @property {String} label 左侧标题
* @property {String} placeholder 输入框的提示文字
* @property {Boolean} disabled 是否禁用
* @property {String} placement 弹出位置
* @value top 顶部弹出
* @value bottom 底部弹出(default)
* @event {Function} change 选中发生变化触发
*/
export default {
name: "uni-data-select",
mixins: [uniCloud.mixinDatacom || {}],
props: {
localdata: {
type: Array,
default () {
return []
}
},
value: {
type: [String, Number],
default: ''
},
modelValue: {
type: [String, Number],
default: ''
},
label: {
type: String,
default: ''
},
placeholder: {
type: String,
default: '请选择'
},
emptyTips: {
type: String,
default: '无选项'
},
clear: {
type: Boolean,
default: true
},
defItem: {
type: Number,
default: 0
},
disabled: {
type: Boolean,
default: false
},
// 格式化输出 用法 field="_id as value, version as text, uni_platform as label" format="{label} - {text}"
format: {
type: String,
default: ''
},
placement: {
type: String,
default: 'bottom'
}
},
data() {
return {
showSelector: false,
current: '',
mixinDatacomResData: [],
apps: [],
channels: [],
cacheKey: "uni-data-select-lastSelectedValue",
};
},
created() {
this.debounceGet = this.debounce(() => {
this.query();
}, 300);
if (this.collection && !this.localdata.length) {
this.debounceGet();
}
},
computed: {
typePlaceholder() {
const text = {
'opendb-stat-app-versions': '版本',
'opendb-app-channels': '渠道',
'opendb-app-list': '应用'
}
const common = this.placeholder
const placeholder = text[this.collection]
return placeholder ?
common + placeholder :
common
},
valueCom() {
// #ifdef VUE3
return this.modelValue;
// #endif
// #ifndef VUE3
return this.value;
// #endif
},
textShow() {
// 长文本显示
let text = this.current;
if (text.length > 10) {
return text.slice(0, 25) + '...';
}
return text;
},
getOffsetByPlacement() {
switch (this.placement) {
case 'top':
return "bottom:calc(100% + 12px);";
case 'bottom':
return "top:calc(100% + 12px);";
}
}
},
watch: {
localdata: {
immediate: true,
handler(val, old) {
if (Array.isArray(val) && old !== val) {
this.mixinDatacomResData = val
}
}
},
valueCom(val, old) {
this.initDefVal()
},
mixinDatacomResData: {
immediate: true,
handler(val) {
if (val.length) {
this.initDefVal()
}
}
},
},
methods: {
debounce(fn, time = 100) {
let timer = null
return function(...args) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
fn.apply(this, args)
}, time)
}
},
// 执行数据库查询
query() {
this.mixinDatacomEasyGet();
},
// 监听查询条件变更事件
onMixinDatacomPropsChange() {
if (this.collection) {
this.debounceGet();
}
},
initDefVal() {
let defValue = ''
if ((this.valueCom || this.valueCom === 0) && !this.isDisabled(this.valueCom)) {
defValue = this.valueCom
} else {
let strogeValue
if (this.collection) {
strogeValue = this.getCache()
}
if (strogeValue || strogeValue === 0) {
defValue = strogeValue
} else {
let defItem = ''
if (this.defItem > 0 && this.defItem <= this.mixinDatacomResData.length) {
defItem = this.mixinDatacomResData[this.defItem - 1].value
}
defValue = defItem
}
if (defValue || defValue === 0) {
this.emit(defValue)
}
}
const def = this.mixinDatacomResData.find(item => item.value === defValue)
this.current = def ? this.formatItemName(def) : ''
},
/**
* @param {[String, Number]} value
* 判断用户给的 value 是否同时为禁用状态
*/
isDisabled(value) {
let isDisabled = false;
this.mixinDatacomResData.forEach(item => {
if (item.value === value) {
isDisabled = item.disable
}
})
return isDisabled;
},
clearVal() {
this.emit('')
if (this.collection) {
this.removeCache()
}
},
change(item) {
if (!item.disable) {
this.showSelector = false
this.current = this.formatItemName(item)
this.emit(item.value)
}
},
emit(val) {
this.$emit('input', val)
this.$emit('update:modelValue', val)
this.$emit('change', val)
if (this.collection) {
this.setCache(val);
}
},
toggleSelector() {
if (this.disabled) {
return
}
this.showSelector = !this.showSelector
},
formatItemName(item) {
let {
text,
value,
channel_code
} = item
channel_code = channel_code ? `(${channel_code})` : ''
if (this.format) {
// 格式化输出
let str = "";
str = this.format;
for (let key in item) {
str = str.replace(new RegExp(`{${key}}`, "g"), item[key]);
}
return str;
} else {
return this.collection.indexOf('app-list') > 0 ?
`${text}(${value})` :
(
text ?
text :
`未命名${channel_code}`
)
}
},
// 获取当前加载的数据
getLoadData() {
return this.mixinDatacomResData;
},
// 获取当前缓存key
getCurrentCacheKey() {
return this.collection;
},
// 获取缓存
getCache(name = this.getCurrentCacheKey()) {
let cacheData = uni.getStorageSync(this.cacheKey) || {};
return cacheData[name];
},
// 设置缓存
setCache(value, name = this.getCurrentCacheKey()) {
let cacheData = uni.getStorageSync(this.cacheKey) || {};
cacheData[name] = value;
uni.setStorageSync(this.cacheKey, cacheData);
},
// 删除缓存
removeCache(name = this.getCurrentCacheKey()) {
let cacheData = uni.getStorageSync(this.cacheKey) || {};
delete cacheData[name];
uni.setStorageSync(this.cacheKey, cacheData);
},
}
}
</script>
<style lang="scss">
$uni-base-color: #6a6a6a !default;
$uni-main-color: #333 !default;
$uni-secondary-color: #909399 !default;
$uni-border-3: #e5e5e5;
/* #ifndef APP-NVUE */
@media screen and (max-width: 500px) {
.hide-on-phone {
display: none;
}
}
/* #endif */
.uni-stat__select {
display: flex;
align-items: center;
// padding: 15px;
/* #ifdef H5 */
cursor: pointer;
/* #endif */
width: 100%;
flex: 1;
box-sizing: border-box;
}
.uni-stat-box {
width: 100%;
flex: 1;
}
.uni-stat__actived {
width: 100%;
flex: 1;
// outline: 1px solid #2979ff;
}
.uni-label-text {
font-size: 14px;
font-weight: bold;
color: $uni-base-color;
margin: auto 0;
margin-right: 5px;
}
.uni-select {
font-size: 14px;
border: 1px solid $uni-border-3;
box-sizing: border-box;
border-radius: 4px;
padding: 0 5px;
padding-left: 10px;
position: relative;
/* #ifndef APP-NVUE */
display: flex;
user-select: none;
/* #endif */
flex-direction: row;
align-items: center;
border-bottom: solid 1px $uni-border-3;
width: 100%;
flex: 1;
height: 35px;
&--disabled {
background-color: #f5f7fa;
cursor: not-allowed;
}
}
.uni-select__label {
font-size: 16px;
// line-height: 22px;
height: 35px;
padding-right: 10px;
color: $uni-secondary-color;
}
.uni-select__input-box {
height: 35px;
position: relative;
/* #ifndef APP-NVUE */
display: flex;
/* #endif */
flex: 1;
flex-direction: row;
align-items: center;
}
.uni-select__input {
flex: 1;
font-size: 14px;
height: 22px;
line-height: 22px;
}
.uni-select__input-plac {
font-size: 14px;
color: $uni-secondary-color;
}
.uni-select__selector {
/* #ifndef APP-NVUE */
box-sizing: border-box;
/* #endif */
position: absolute;
left: 0;
width: 100%;
background-color: #FFFFFF;
border: 1px solid #EBEEF5;
border-radius: 6px;
box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
z-index: 3;
padding: 4px 0;
}
.uni-select__selector-scroll {
/* #ifndef APP-NVUE */
max-height: 200px;
box-sizing: border-box;
/* #endif */
}
/* #ifdef H5 */
@media (min-width: 768px) {
.uni-select__selector-scroll {
max-height: 600px;
}
}
/* #endif */
.uni-select__selector-empty,
.uni-select__selector-item {
/* #ifndef APP-NVUE */
display: flex;
cursor: pointer;
/* #endif */
line-height: 35px;
font-size: 14px;
text-align: center;
/* border-bottom: solid 1px $uni-border-3; */
padding: 0px 10px;
}
.uni-select__selector-item:hover {
background-color: #f9f9f9;
}
.uni-select__selector-empty:last-child,
.uni-select__selector-item:last-child {
/* #ifndef APP-NVUE */
border-bottom: none;
/* #endif */
}
.uni-select__selector__disabled {
opacity: 0.4;
cursor: default;
}
/* picker 弹出层通用的指示小三角 */
.uni-popper__arrow_bottom,
.uni-popper__arrow_bottom::after,
.uni-popper__arrow_top,
.uni-popper__arrow_top::after,
{
position: absolute;
display: block;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 6px;
}
.uni-popper__arrow_bottom {
filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
top: -6px;
left: 10%;
margin-right: 3px;
border-top-width: 0;
border-bottom-color: #EBEEF5;
}
.uni-popper__arrow_bottom::after {
content: " ";
top: 1px;
margin-left: -6px;
border-top-width: 0;
border-bottom-color: #fff;
}
.uni-popper__arrow_top {
filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
bottom: -6px;
left: 10%;
margin-right: 3px;
border-bottom-width: 0;
border-top-color: #EBEEF5;
}
.uni-popper__arrow_top::after {
content: " ";
bottom: 1px;
margin-left: -6px;
border-bottom-width: 0;
border-top-color: #fff;
}
.uni-select__input-text {
// width: 280px;
width: 100%;
color: $uni-main-color;
white-space: nowrap;
text-overflow: ellipsis;
-o-text-overflow: ellipsis;
overflow: hidden;
}
.uni-select__input-placeholder {
color: $uni-base-color;
font-size: 12px;
}
.uni-select--mask {
position: fixed;
top: 0;
bottom: 0;
right: 0;
left: 0;
z-index: 2;
}
</style>
@@ -0,0 +1,86 @@
{
"id": "uni-data-select",
"displayName": "uni-data-select 下拉框选择器",
"version": "1.0.8",
"description": "通过数据驱动的下拉框选择器",
"keywords": [
"uni-ui",
"select",
"uni-data-select",
"下拉框",
"下拉选"
],
"repository": "https://github.com/dcloudio/uni-ui",
"engines": {
"HBuilderX": "^3.1.1"
},
"directories": {
"example": "../../temps/example_temps"
},
"dcloudext": {
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": "https://www.npmjs.com/package/@dcloudio/uni-ui",
"type": "component-vue"
},
"uni_modules": {
"dependencies": ["uni-load-more"],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y",
"alipay": "n"
},
"client": {
"App": {
"app-vue": "u",
"app-nvue": "n"
},
"H5-mobile": {
"Safari": "y",
"Android Browser": "y",
"微信浏览器(Android)": "y",
"QQ浏览器(Android)": "y"
},
"H5-pc": {
"Chrome": "y",
"IE": "y",
"Edge": "y",
"Firefox": "y",
"Safari": "y"
},
"小程序": {
"微信": "y",
"阿里": "u",
"百度": "u",
"字节跳动": "u",
"QQ": "u",
"京东": "u"
},
"快应用": {
"华为": "u",
"联盟": "u"
},
"Vue": {
"vue2": "y",
"vue3": "y"
}
}
}
}
}
@@ -0,0 +1,8 @@
## DataSelect 下拉框选择器
> **组件名:uni-data-select**
> 代码块: `uDataSelect`
当选项过多时,使用下拉菜单展示并选择内容
### [查看文档](https://uniapp.dcloud.io/component/uniui/uni-data-select)
#### 如使用过程中有任何问题,或者您对uni-ui有一些好的建议,欢迎加入 uni-ui 交流群:871950839
@@ -0,0 +1,10 @@
## 1.0.0(2021-11-19)
- 优化 组件UI,并提供设计资源,详见:[https://uniapp.dcloud.io/component/uniui/resource](https://uniapp.dcloud.io/component/uniui/resource)
- 文档迁移,详见:[https://uniapp.dcloud.io/component/uniui/uni-dateformat](https://uniapp.dcloud.io/component/uniui/uni-dateformat)
## 0.0.5(2021-07-08)
- 调整 默认时间不再是当前时间,而是显示'-'字符
## 0.0.4(2021-05-12)
- 新增 组件示例地址
## 0.0.3(2021-02-04)
- 调整为uni_modules目录规范
- 修复 iOS 平台日期格式化出错的问题
@@ -0,0 +1,200 @@
// yyyy-MM-dd hh:mm:ss.SSS 所有支持的类型
function pad(str, length = 2) {
str += ''
while (str.length < length) {
str = '0' + str
}
return str.slice(-length)
}
const parser = {
yyyy: (dateObj) => {
return pad(dateObj.year, 4)
},
yy: (dateObj) => {
return pad(dateObj.year)
},
MM: (dateObj) => {
return pad(dateObj.month)
},
M: (dateObj) => {
return dateObj.month
},
dd: (dateObj) => {
return pad(dateObj.day)
},
d: (dateObj) => {
return dateObj.day
},
hh: (dateObj) => {
return pad(dateObj.hour)
},
h: (dateObj) => {
return dateObj.hour
},
mm: (dateObj) => {
return pad(dateObj.minute)
},
m: (dateObj) => {
return dateObj.minute
},
ss: (dateObj) => {
return pad(dateObj.second)
},
s: (dateObj) => {
return dateObj.second
},
SSS: (dateObj) => {
return pad(dateObj.millisecond, 3)
},
S: (dateObj) => {
return dateObj.millisecond
},
}
// 这都n年了iOS依然不认识2020-12-12,需要转换为2020/12/12
function getDate(time) {
if (time instanceof Date) {
return time
}
switch (typeof time) {
case 'string':
{
// 2020-12-12T12:12:12.000Z、2020-12-12T12:12:12.000
if (time.indexOf('T') > -1) {
return new Date(time)
}
return new Date(time.replace(/-/g, '/'))
}
default:
return new Date(time)
}
}
export function formatDate(date, format = 'yyyy/MM/dd hh:mm:ss') {
if (!date && date !== 0) {
return ''
}
date = getDate(date)
const dateObj = {
year: date.getFullYear(),
month: date.getMonth() + 1,
day: date.getDate(),
hour: date.getHours(),
minute: date.getMinutes(),
second: date.getSeconds(),
millisecond: date.getMilliseconds()
}
const tokenRegExp = /yyyy|yy|MM|M|dd|d|hh|h|mm|m|ss|s|SSS|SS|S/
let flag = true
let result = format
while (flag) {
flag = false
result = result.replace(tokenRegExp, function(matched) {
flag = true
return parser[matched](dateObj)
})
}
return result
}
export function friendlyDate(time, {
locale = 'zh',
threshold = [60000, 3600000],
format = 'yyyy/MM/dd hh:mm:ss'
}) {
if (time === '-') {
return time
}
if (!time && time !== 0) {
return ''
}
const localeText = {
zh: {
year: '年',
month: '月',
day: '天',
hour: '小时',
minute: '分钟',
second: '秒',
ago: '前',
later: '后',
justNow: '刚刚',
soon: '马上',
template: '{num}{unit}{suffix}'
},
en: {
year: 'year',
month: 'month',
day: 'day',
hour: 'hour',
minute: 'minute',
second: 'second',
ago: 'ago',
later: 'later',
justNow: 'just now',
soon: 'soon',
template: '{num} {unit} {suffix}'
}
}
const text = localeText[locale] || localeText.zh
let date = getDate(time)
let ms = date.getTime() - Date.now()
let absMs = Math.abs(ms)
if (absMs < threshold[0]) {
return ms < 0 ? text.justNow : text.soon
}
if (absMs >= threshold[1]) {
return formatDate(date, format)
}
let num
let unit
let suffix = text.later
if (ms < 0) {
suffix = text.ago
ms = -ms
}
const seconds = Math.floor((ms) / 1000)
const minutes = Math.floor(seconds / 60)
const hours = Math.floor(minutes / 60)
const days = Math.floor(hours / 24)
const months = Math.floor(days / 30)
const years = Math.floor(months / 12)
switch (true) {
case years > 0:
num = years
unit = text.year
break
case months > 0:
num = months
unit = text.month
break
case days > 0:
num = days
unit = text.day
break
case hours > 0:
num = hours
unit = text.hour
break
case minutes > 0:
num = minutes
unit = text.minute
break
default:
num = seconds
unit = text.second
break
}
if (locale === 'en') {
if (num === 1) {
num = 'a'
} else {
unit += 's'
}
}
return text.template.replace(/{\s*num\s*}/g, num + '').replace(/{\s*unit\s*}/g, unit).replace(/{\s*suffix\s*}/g,
suffix)
}

Some files were not shown because too many files have changed in this diff Show More