Browse Source

feat: 添加购物车功能并优化代码结构

refactor: 重构验证函数和API调用逻辑

fix: 修复z-index过高问题并优化样式

docs: 更新注释和文档说明

style: 统一代码格式和命名规范

chore: 更新.gitignore和package.json配置

test: 添加异步函数状态检查工具函数
master
wei 1 week ago
parent
commit
d2a95b9d0e
  1. 1
      .gitignore
  2. 4
      components/navigation/navigation.vue
  3. 9
      eslint.config.mjs
  4. 31
      libs/api/index.js
  5. 10
      libs/utils/config.js
  6. 34
      libs/utils/crypto.js
  7. 51
      libs/utils/index.js
  8. 82
      libs/utils/isPending.js
  9. 12
      package.json
  10. 6
      pages/agreement/agreement.vue
  11. 2
      pages/classification/classification.scss
  12. 178
      pages/classification/classification.vue
  13. 88
      pages/home/home.vue
  14. 40
      pages/home/honest.vue
  15. 4
      pages/index/index.vue
  16. 133
      pages/login/login.vue
  17. 24
      pages/personalInformation/personalInformation.vue
  18. 2
      store/index.js

1
.gitignore

@ -11,6 +11,7 @@ dist/
npm-debug.log* npm-debug.log*
yarn-debug.log* yarn-debug.log*
yarn-error.log* yarn-error.log*
.gitbk
# Editor directories and files # Editor directories and files
.project .project

4
components/navigation/navigation.vue

@ -1,6 +1,6 @@
<script setup> <script setup>
import { onLoad, onShow } from "@dcloudio/uni-app";
import { defineProps, nextTick, onBeforeUnmount, onMounted, ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { defineProps, ref } from "vue";
const props = defineProps({ const props = defineProps({
title: { title: {

9
eslint.config.mjs

@ -20,6 +20,7 @@ export default antfu({
"vue/eqeqeq": ["off"], "vue/eqeqeq": ["off"],
"vue/require-prop-type-constructor": ["off"], "vue/require-prop-type-constructor": ["off"],
"eqeqeq": ["off"], "eqeqeq": ["off"],
"no-console": ["off"],
}, },
ignores: [ ignores: [
"uni_modules/**/*", "uni_modules/**/*",
@ -28,5 +29,13 @@ export default antfu({
"unpackage/**/*", "unpackage/**/*",
"uniCloud-aliyun/**/*", "uniCloud-aliyun/**/*",
"utils/css.js", "utils/css.js",
"types/global.d.ts",
"manifest.json",
"node_modules/**/*",
"unpackage/**/*",
"uni.promisify.adaptor.js",
"pages.json",
"css.js",
"androidPrivacy.json",
], ],
}); });

31
libs/api/index.js

@ -271,7 +271,7 @@ export function getUserTreatyApi(data) {
/** /**
* 登录 * 登录
* @param {*} data
* @param {{username: string, password: string}} data
*/ */
export function loginApi(data = {}) { export function loginApi(data = {}) {
return request({ return request({
@ -302,9 +302,36 @@ export function yesterdayOrderApi() {
export function getCartInfoApi(params = {}) { export function getCartInfoApi(params = {}) {
return request({ return request({
errorMessage: "购物车",
errorMessage: "购物车信息",
method: "GET", method: "GET",
params, params,
url: "/cart/list.do", url: "/cart/list.do",
}); });
} }
/**
* 加入购物车
* @param {*} data
*/
export function addCartApi(data = {}) {
// request('/cart/add.do', 'POST', postData, success);
return request({
errorMessage: "购物车",
method: "POST",
data,
url: "/cart/add.do",
});
}
/**
* 订单预览
* @param {*} params
*/
export function previewApi(params = {}) {
return request({
errorMessage: "订单预览",
method: "GET",
params,
url: "/order/preview.do",
});
}

10
libs/utils/config.js

@ -1,5 +1,11 @@
const SECRET_KEY = 'a1b2c3d4e5f678901234567890abcdefa1b2c3d4e5f678901234567890abcdef';
/**
* 加密密钥
*/
const SECRET_KEY = "a1b2c3d4e5f678901234567890abcdefa1b2c3d4e5f678901234567890abcdef";
/**
* @property {string} SECRET_KEY 加密密钥
*/
export default { export default {
SECRET_KEY, SECRET_KEY,
};
};

34
libs/utils/crypto.js

@ -1,31 +1,31 @@
import CryptoJS from 'crypto-js';
import secretKey from './config.js';
import CryptoJS from "crypto-js";
// import secretKey from './config.js';
// 解决App端没有window.crypto的问题 // 解决App端没有window.crypto的问题
if (typeof window === 'undefined' || !window.crypto) {
// 提供自定义随机数生成器
CryptoJS.lib.WordArray.random = function(nBytes) {
const words = [];
for (let i = 0; i < nBytes; i += 4) {
// 使用uniapp的随机数API或Math.random()生成
words.push(((Math.random() * 0x100000000) | 0) << 0);
}
return new CryptoJS.lib.WordArray.init(words, nBytes);
};
if (typeof window === "undefined" || !window.crypto) {
// 提供自定义随机数生成器
CryptoJS.lib.WordArray.random = function (nBytes) {
const words = [];
for (let i = 0; i < nBytes; i += 4) {
// 使用uniapp的随机数API或Math.random()生成
words.push(((Math.random() * 0x100000000) | 0) << 0);
}
const Init = CryptoJS.lib.WordArray.init;
return new Init(words, nBytes);
};
} }
// 加密函数 // 加密函数
export function encryptData(data, secretKey) { export function encryptData(data, secretKey) {
return CryptoJS.AES.encrypt(JSON.stringify(data), secretKey).toString();
return CryptoJS.AES.encrypt(JSON.stringify(data), secretKey).toString();
} }
// 解密函数 // 解密函数
export function decryptData(ciphertext, secretKey) { export function decryptData(ciphertext, secretKey) {
const bytes = CryptoJS.AES.decrypt(ciphertext, secretKey);
return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
const bytes = CryptoJS.AES.decrypt(ciphertext, secretKey);
return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
} }
// 使用示例 // 使用示例
// const secretKey = secretKey; // 替换为你的密钥 // const secretKey = secretKey; // 替换为你的密钥
// const dataToStore = { key: 'value' }; // const dataToStore = { key: 'value' };
@ -39,4 +39,4 @@ export function decryptData(ciphertext, secretKey) {
// const decryptedData = decryptData(res.data, secretKey); // const decryptedData = decryptData(res.data, secretKey);
// console.log(decryptedData); // 输出解密后的数据 // console.log(decryptedData); // 输出解密后的数据
// } // }
// });
// });

51
libs/utils/index.js

@ -1,3 +1,5 @@
// import { isAsync } from "./isPending";
const _promiseThrottleMap = {}; const _promiseThrottleMap = {};
/** /**
@ -25,6 +27,14 @@ export function promiseThrottle(promise_id, time = 500, promiseFunction, onTime)
}); });
} }
export function sleep(timeout = 3000) {
return new Promise((resolve) => {
setTimeout(() => {
resolve();
}, timeout);
});
}
/** /**
* status 状态栏 | menu 小程序胶囊 | screen 屏幕 * status 状态栏 | menu 小程序胶囊 | screen 屏幕
* @returns {{ * @returns {{
@ -98,25 +108,50 @@ export function gotoBack() {
} }
} }
/**
* toast配置
* @typedef {object} toastConfig
* @property {string} title - toast标题
* @property {string} icon - toast图标默认none
* @property {boolean} returnBoolean - 是否返回字符串默认返回布尔值
*/
/** /**
* 校验器 * 校验器
* @example * @example
* const validators = [ * const validators = [
* () => name || "请输入姓名",
* () => !email && "请输入邮箱", // && if true: return msge * () => !email && "请输入邮箱", // && if true: return msge
* ]; * ];
* validates(validators); * validates(validators);
* @param {Array<Function>|Function} validators 校验函数数组每个函数返回校验错误信息或空字符串 * @param {Array<Function>|Function} validators 校验函数数组每个函数返回校验错误信息或空字符串
* @param {boolean} returnBoolean 是否返回布尔值默认返回字符串
* @param {toastConfig} toastConfig 校验失败时的toast配置
* @returns {string|boolean} 校验错误信息或空字符串 * @returns {string|boolean} 校验错误信息或空字符串
*/ */
export function validates(validators, returnBoolean = true) {
for (const callback of [validators].flat()) {
const msg = callback();
export function validates(validators, toastConfig = { icon: "none", returnBoolean: true }) {
const validatorsFlat = Array.isArray(validators) ? validators : [validators];
// const hasAsync = validatorsFlat.some(item => isAsync(item));
// if (!hasAsync) {
// 同步校验:顺序执行,遇到第一条错误立即返回
for (const validator of validatorsFlat) {
const msg = validator();
if (msg) { if (msg) {
uni.showToast({ title: msg });
return returnBoolean ? false : msg;
console.log(msg, "校验失败");
return toastConfig.returnBoolean ? false : msg;
} }
} }
return returnBoolean ? true : "";
return toastConfig.returnBoolean ? true : "";
// }
// else {
// // 异步校验:顺序执行,遇到第一条错误立即返回
// return (async () => {
// for (const validator of validatorsFlat) {
// const msg = await validator();
// if (msg) {
// console.log(msg, "校验失败");
// return toastConfig.returnBoolean ? false : msg;
// }
// }
// return toastConfig.returnBoolean ? true : "";
// })();
// }
} }

82
libs/utils/isPending.js

@ -0,0 +1,82 @@
/**
* 检查目标是否为pending状态的Promise或异步函数
* @param {*} target 要检查的目标可接受Promise异步函数或同步函数
* @returns {Promise<boolean>} 一个Promise解析为目标是否为pending状态
*/
async function isPending(target) {
// 如果是异步函数,执行后检查返回的Promise状态
if (isAsyncFunction(target)) {
try {
const promise = target();
return await checkPromisePending(promise);
}
// eslint-disable-next-line unused-imports/no-unused-vars
catch (error) {
return false; // 异步函数执行出错,不是pending状态
}
}
// 如果是Promise对象,直接检查状态
if (isPromise(target)) {
return await checkPromisePending(target);
}
return false; // 既不是异步函数也不是Promise
}
/**
* 检查是否为异步函数
* @param {*} fn 要检查的函数
* @returns {boolean} 是否为异步函数
*/
function isAsyncFunction(fn) {
return typeof fn === "function"
&& (fn.constructor.name === "AsyncFunction"
|| fn.toString().includes("async"));
}
/**
* 检查是否为Promise
* @param {*} obj 要检查的对象
* @returns {boolean} 是否为Promise
*/
function isPromise(obj) {
return obj instanceof Promise
|| (obj && typeof obj.then === "function");
}
/**
* 检查Promise是否为pending状态
* @param {Promise} promise 要检查的Promise对象
* @returns {Promise<boolean>} 一个Promise解析为Promise是否为pending状态
*/
async function checkPromisePending(promise) {
const pending = Symbol("pending");
try {
const result = await Promise.race([
promise.then(
() => "fulfilled",
() => "rejected",
),
Promise.resolve(pending),
]);
return result === pending;
}
// eslint-disable-next-line unused-imports/no-unused-vars
catch (error) {
return false; // Promise已经rejected
}
}
/**
* 检查是否为Promise或异步函数
* @param {*} target 要检查的目标
* @returns {boolean} 是否为Promise或异步函数
*/
function isAsync(target) {
return isPromise(target) || isAsyncFunction(target);
}
export { isAsync, isPending };

12
package.json

@ -8,15 +8,17 @@
"keywords": [], "keywords": [],
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"devDependencies": {
"@antfu/eslint-config": "^5.4.1",
"eslint": "^9.37.0"
"test": "echo \"Error: no test specified\" && exit 1",
"lint": "eslint --ext pages",
"format": "eslint --ext pages --fix"
}, },
"dependencies": { "dependencies": {
"crypto-js": "^4.2.0", "crypto-js": "^4.2.0",
"moment": "^2.30.1", "moment": "^2.30.1",
"pinia": "^3.0.3" "pinia": "^3.0.3"
},
"devDependencies": {
"@antfu/eslint-config": "^5.4.1",
"eslint": "^9.37.0"
} }
} }

6
pages/agreement/agreement.vue

@ -9,11 +9,7 @@ const title = ref("");
onLoad(() => { onLoad(() => {
const instance = getCurrentInstance().proxy; const instance = getCurrentInstance().proxy;
const eventChannel = instance.getOpenerEventChannel(); const eventChannel = instance.getOpenerEventChannel();
eventChannel.on("privacyAgreement", (data) => {
html.value = data.html;
title.value = data.title;
});
eventChannel.on("serviceAgreement", (data) => {
eventChannel.on("html", (data) => {
html.value = data.html; html.value = data.html;
title.value = data.title; title.value = data.title;
}); });

2
pages/classification/classification.scss

@ -741,7 +741,7 @@ page {
margin-top: 5rpx; margin-top: 5rpx;
padding-top: 12rpx; padding-top: 12rpx;
position: relative; position: relative;
z-index: 999999;
z-index: 999;
background-color: #fff; background-color: #fff;
border-bottom: 1px solid #CCCCCC; border-bottom: 1px solid #CCCCCC;

178
pages/classification/classification.vue

@ -3,11 +3,20 @@ import { onShow } from "@dcloudio/uni-app";
import { nextTick, ref } from "vue"; import { nextTick, ref } from "vue";
import customTabBar from "@/components/custom-tab-bar/my-tab-bar.vue"; import customTabBar from "@/components/custom-tab-bar/my-tab-bar.vue";
import navigation from "@/components/navigation/navigation.vue"; import navigation from "@/components/navigation/navigation.vue";
import { getCartInfoApi, getProductsApi, getProductTypesApi } from "@/libs/api";
import {
addCartApi,
getCartInfoApi,
getProductsApi,
getProductTypesApi,
previewApi,
} from "@/libs/api";
import { getHeight, useHeight, validates } from "@/libs/utils"; import { getHeight, useHeight, validates } from "@/libs/utils";
import useStore from "@/store"; import useStore from "@/store";
const store = useStore(); const store = useStore();
/**
* 购物车商品id列表
*/
const keys = []; const keys = [];
// const plugin = requirePlugin("WechatSI") // const plugin = requirePlugin("WechatSI")
@ -69,6 +78,30 @@ const typeData = ref([]);
* 商品数据 * 商品数据
*/ */
const products = ref([]); const products = ref([]);
/**
* 购物车商品数量
*/
const cartCount = ref(0);
/**
* 购物车商品列表
*/
const cartList = ref([]);
/**
* 购物车商品总价
*/
const totalPrice = ref(0);
/**
* 服务费用
*/
const serviceFee = ref(0);
/**
* 配送费
*/
const shippingFee = ref(0);
/**
* 是否显示购物车
*/
const showCart = ref(false);
/** /**
* 判断商品列表滚动到底部是否还有数据 * 判断商品列表滚动到底部是否还有数据
*/ */
@ -132,7 +165,7 @@ const hasFetchedCart = ref(true);
/** /**
* 上次点击加入购物车的时间 * 上次点击加入购物车的时间
*/ */
const actionTime = ref(true);
// const actionTime = ref(true);
/** /**
* 输入购买数量弹框的值 * 输入购买数量弹框的值
*/ */
@ -140,7 +173,7 @@ const inputValue = ref("");
/** /**
* 隐藏购买数量弹框 * 隐藏购买数量弹框
*/ */
const hiddenModal = ref(true);
// const hiddenModal = ref(true);
function onSearch() {} function onSearch() {}
@ -178,22 +211,23 @@ function onSwitchType(item, index) {
if (currentType.value === index) if (currentType.value === index)
return; return;
currentType.value = index; currentType.value = index;
// products.value = [];
// unLoading.value = false;
// showList.value = true;
// pageIndex.value = 1;
products.value = [];
unLoading.value = false;
showList.value = true;
pageIndex.value = 1;
scrollId.value = item.id; scrollId.value = item.id;
getProducts(scrollId.value);
} }
/** /**
* 获取顶部tab标签列表,对应左侧类别 * 获取顶部tab标签列表,对应左侧类别
*/ */
async function getProductTypes(id, isSearch) { async function getProductTypes(id, isSearch) {
const resp = await getProductTypesApi();
if (resp.code === "0") {
navData.value = resp.data;
const res = await getProductTypesApi();
if (res.code === "0") {
navData.value = res.data;
if (id) { if (id) {
getLeftTypes(id); getLeftTypes(id);
resp.data.forEach((item, index) => {
res.data.forEach((item, index) => {
if (item.id === id) { if (item.id === id) {
currentTab.value = index; currentTab.value = index;
navScrollLeft.value = (index - 2) * 50; navScrollLeft.value = (index - 2) * 50;
@ -212,11 +246,11 @@ async function getProductTypes(id, isSearch) {
* @param isSearch * @param isSearch
*/ */
async function getLeftTypes(parentId, isSearch) { async function getLeftTypes(parentId, isSearch) {
const resp = await getProductTypesApi({ parentId });
if (resp.code === "0") {
typeData.value = resp.data;
const res = await getProductTypesApi({ parentId });
if (res.code === "0") {
typeData.value = res.data;
if (resp.total > 0) {
if (res.total > 0) {
scrollId.value = typeData.value[currentType.value].id; scrollId.value = typeData.value[currentType.value].id;
getProducts(isSearch ? "" : scrollId.value); getProducts(isSearch ? "" : scrollId.value);
} }
@ -231,10 +265,10 @@ async function getProducts(parentId, tips) {
warehouseId: uni.getStorageSync("warehousId"), warehouseId: uni.getStorageSync("warehousId"),
addrId: uni.getStorageSync("addressId"), addrId: uni.getStorageSync("addressId"),
}; };
const resp = await getCartInfoApi(params);
store.changeCartList(resp.code === "0" ? resp.data : []);
// app.globalData.cartList = resp.code === "0" ? resp.data : [];
hasFetchedCart.value = resp.code === "0";
const res = await getCartInfoApi(params);
store.changeCartList(res.code === "0" ? res.data : []);
// app.globalData.cartList = res.code === "0" ? res.data : [];
hasFetchedCart.value = res.code === "0";
} }
loadProductList(parentId, tips); loadProductList(parentId, tips);
@ -264,18 +298,18 @@ async function loadProductList(parentId, tips) {
warehouseid: uni.getStorageSync("warehousId"), warehouseid: uni.getStorageSync("warehousId"),
}; };
const resp = await getProductsApi(params);
if (resp.code !== "0")
const res = await getProductsApi(params);
if (res.code !== "0")
return; return;
pageCount.value = resp.pageCount;
pageCount.value = res.pageCount;
if (!(resp.total > 0)) {
if (!(res.total > 0)) {
showList.value = false; showList.value = false;
return; return;
} }
resp.data.forEach((item) => {
res.data.forEach((item) => {
// specId_price -> quantity // specId_price -> quantity
const cartMap = cartList.reduce((acc, cur) => { const cartMap = cartList.reduce((acc, cur) => {
return { ...acc, [`${cur.specId}_${cur.price}`]: cur.quantity }; return { ...acc, [`${cur.specId}_${cur.price}`]: cur.quantity };
@ -294,8 +328,8 @@ async function loadProductList(parentId, tips) {
}); });
products.value = pageIndex.value === 1 products.value = pageIndex.value === 1
? resp.data
: [...products.value, ...(resp.data || [])];
? res.data
: [...products.value, ...(res.data || [])];
rightHeight.value = (await getHeight("#scroll-page")) + 1; rightHeight.value = (await getHeight("#scroll-page")) + 1;
if (tips === 1) { if (tips === 1) {
@ -430,11 +464,48 @@ function onGotoDetail(item) {
url: `/pages/detail/detail?id=${item.id}`, url: `/pages/detail/detail?id=${item.id}`,
}); });
} }
/**
* 初始化购物车信息
*/
async function initCartInfo() {
const data = {
warehouseId: uni.getStorageSync("warehousId"),
addrId: uni.getStorageSync("addressId"),
};
const res = await getCartInfoApi(data);
if (res.code !== 0)
return;
cartCount.value = res.total;
cartList.value = res.data || [];
store.goodsCheckedItems = res.data.map(item => item.id); ;
totalPrice.value = res.data.reduce((acc, item) => acc + item.amount, 0).toFixed(2);
if (store.goodsCheckedItems > 0) {
preview(store.goodsCheckedItems);
}
else if (showCart.value) {
showList.value = false;
}
}
/**
* 订单预览
* @param itemIds 商品id列表
*/
async function preview(itemIds) {
const data = {
itemIds: itemIds.join(","),
addrId: uni.getStorageSync("addressId"),
};
const res = await previewApi(data);
serviceFee.value = res.data.serviceFee;
shippingFee.value = res.data.shippingFee;
totalPrice.value = res.data.itemAmount;
}
/** /**
* 加入购物车 * 加入购物车
* @param item 商品项 * @param item 商品项
*/ */
function onAdd(item) {
async function onAdd(item) {
// item.specs[0].sum = 9; // item.specs[0].sum = 9;
// if (item.sum === "") { // if (item.sum === "") {
// item.sum = inputValue.value; // item.sum = inputValue.value;
@ -454,6 +525,51 @@ function onAdd(item) {
item.sum += item.sum === 0 ? (item.minNum || 1) : 1; item.sum += item.sum === 0 ? (item.minNum || 1) : 1;
// //
inputValue.value = item.sum; inputValue.value = item.sum;
toCart(item);
}
/**
* 更新购物车
* @param item 商品项
*/
async function toCart(item) {
const data = {
quantity: item.sum,
specId: item.id,
Chuxiao: item.chuxiao,
warehouseId: uni.getStorageSync("warehousId"),
addrId: uni.getStorageSync("addressId"),
};
if (!data.specId) {
uni.showModal({
title: "提示",
content: "当前商品规格错误,请稍候再试",
showCancel: false,
confirmText: "确定",
});
}
if (data.Chuxiao === "" || data.Chuxiao === undefined) {
data.Chuxiao = false;
}
if (!data.warehouseId || !data.addrId) {
uni.showModal({
title: "提示",
content: "请先选择收货地址,再添加商品",
showCancel: false,
confirmText: "确定",
});
}
keys.push(item.id);
const res = await addCartApi(data);
keys.splice(item.id, 1);
if (res.code === "0") {
initCartInfo();
}
} }
/** /**
@ -480,15 +596,17 @@ function onMinus(item) {
item.sum -= item.sum === (item.minNum || 1) ? (item.minNum || 1) : 1; item.sum -= item.sum === (item.minNum || 1) ? (item.minNum || 1) : 1;
// //
inputValue.value = item.sum; inputValue.value = item.sum;
toCart(item);
} }
function onChooseNorm(item) { function onChooseNorm(item) {
item.showChild = !item.showChild; item.showChild = !item.showChild;
} }
function onModelConfirm() { }
// function onModelConfirm() { }
function onModelCancel() { }
// function onModelCancel() { }
function onShowKeyboard() { } function onShowKeyboard() { }
@ -588,7 +706,7 @@ onShow(() => {
v-for="(navItem, idx) in navData" v-for="(navItem, idx) in navData"
:key="idx" :key="idx"
class="listx" class="listx"
@click="onSwitchNav"
@click="() => onSwitchNav(navItem, idx)"
> >
<image <image
class="img" class="img"

88
pages/home/home.vue

@ -1,11 +1,11 @@
<script setup> <script setup>
import { onLoad, onShow } from "@dcloudio/uni-app"; import { onLoad, onShow } from "@dcloudio/uni-app";
import moment from "moment";
// import moment from "moment";
import { nextTick, ref } from "vue"; import { nextTick, ref } from "vue";
import customTabBar from "@/components/custom-tab-bar/my-tab-bar.vue"; import customTabBar from "@/components/custom-tab-bar/my-tab-bar.vue";
import { import {
editDefaultAddressApi,
getBroadcastApi,
// editDefaultAddressApi,
// getBroadcastApi,
getCarouselsApi, getCarouselsApi,
getmyareaApi, getmyareaApi,
getNoticesApi, getNoticesApi,
@ -13,7 +13,7 @@ import {
getProductTypesApi, getProductTypesApi,
getProductTypesHomeApi, getProductTypesHomeApi,
getSystemSettingApi, getSystemSettingApi,
myOrdersApi,
// myOrdersApi,
} from "@/libs/api"; } from "@/libs/api";
// import permissionPopup from "@/components/permissionPopup/permissionPopup.vue"; // import permissionPopup from "@/components/permissionPopup/permissionPopup.vue";
// import checkUpdate from "@/uni_modules/uni-upgrade-center-app/utils/check-update"; // import checkUpdate from "@/uni_modules/uni-upgrade-center-app/utils/check-update";
@ -88,10 +88,10 @@ const newGoods = ref([]);
*/ */
async function getIosShow() { async function getIosShow() {
const params = { black: "XCXenterCDW", key: "config.enterCDW" }; const params = { black: "XCXenterCDW", key: "config.enterCDW" };
const resp = await getSystemSettingApi(params);
const res = await getSystemSettingApi(params);
// 0 // 0
isShowRecruitment.value = resp.data.code !== 0;
// if (resp.data.code === 0) {
isShowRecruitment.value = res.data.code !== 0;
// if (res.data.code === 0) {
// isShowRecruitment.value = false; // isShowRecruitment.value = false;
// menus.value = menus.value.filter(item => item.name !== "" || item.name !== ""); // menus.value = menus.value.filter(item => item.name !== "" || item.name !== "");
// } // }
@ -104,35 +104,35 @@ async function getIosShow() {
*/ */
async function getBanner() { async function getBanner() {
banner.value = []; banner.value = [];
const resp = await getCarouselsApi();
const res = await getCarouselsApi();
swiperCurrent.value = 0; swiperCurrent.value = 0;
bannerAutoplay.value = true; bannerAutoplay.value = true;
banner.value = resp.data;
banner.value = res.data;
isShowBanner.value = true; isShowBanner.value = true;
} }
/** /**
* 获取产品分类 * 获取产品分类
*/ */
async function getProductCategory() { async function getProductCategory() {
const resp = await getProductTypesHomeApi();
types.value = resp.data;
const res = await getProductTypesHomeApi();
types.value = res.data;
} }
/** /**
* 获取公告列表 * 获取公告列表
*/ */
async function getNoticesApiList() { async function getNoticesApiList() {
const resp = await getNoticesApi();
notices.value = resp.data;
const res = await getNoticesApi();
notices.value = res.data;
} }
/** /**
* 获取特价新品商品种类 * 获取特价新品商品种类
*/ */
async function getProductTypes() { async function getProductTypes() {
const resp = await getProductTypesApi();
if (resp.code !== "0") {
const res = await getProductTypesApi();
if (res.code !== "0") {
return; return;
} }
const eachsId = resp.data.reduce((acc, cur) => {
const eachsId = res.data.reduce((acc, cur) => {
if (cur.name === "新品" || cur.name === "特价专区") { if (cur.name === "新品" || cur.name === "特价专区") {
acc.push(cur); acc.push(cur);
} }
@ -143,10 +143,10 @@ async function getProductTypes() {
if (!(each.name === "新品" || each.name === "特价专区")) { if (!(each.name === "新品" || each.name === "特价专区")) {
return; return;
} }
const resp = await getProductTypesApi({ parentId: each.id });
if (resp.code !== "0")
const res = await getProductTypesApi({ parentId: each.id });
if (res.code !== "0")
return; return;
const typeId = resp.data[0].id;
const typeId = res.data[0].id;
const params = { const params = {
typeId, typeId,
promotion: false, promotion: false,
@ -157,12 +157,12 @@ async function getProductTypes() {
pageSize: 5, pageSize: 5,
warehouseid: uni.getStorageSync("warehousId"), warehouseid: uni.getStorageSync("warehousId"),
}; };
const resp2 = await getProductsApi(params);
if (resp2.code !== "0")
const res2 = await getProductsApi(params);
if (res2.code !== "0")
return; return;
// //
resp2.data.forEach((item) => {
res2.data.forEach((item) => {
// //
item.showChoose = (item.specs.length > 1); item.showChoose = (item.specs.length > 1);
// 0 // 0
@ -172,15 +172,15 @@ async function getProductTypes() {
}); });
if (each.name === "新品") { if (each.name === "新品") {
newGoods.value = resp2.data;
newGoods.value = res2.data;
} }
else { else {
products.value = resp2.data;
products.value = res2.data;
} }
} }
} }
function getDFKDataLength() { function getDFKDataLength() {
const nowDay = moment().format("YYYY-MM-DD");
// const nowDay = moment().format("YYYY-MM-DD");
// myOrdersApi({ // myOrdersApi({
// orderNo: "", // orderNo: "",
// status: "DFK", // status: "DFK",
@ -202,12 +202,12 @@ async function getmyarea() {
title: "加载中", title: "加载中",
mask: true, mask: true,
}); });
const resp = await getmyareaApi(postData);
if (resp.code !== "0") {
const res = await getmyareaApi(postData);
if (res.code !== "0") {
uni.hideLoading(); uni.hideLoading();
return; return;
} }
const list = resp.data.list.sort((pre, cur) => Number(cur) - Number(pre));
const list = res.data.list.sort((pre, cur) => Number(cur) - Number(pre));
// each isLastDefaultAddr // each isLastDefaultAddr
const each = list.find(each => each.isLastDefaultAddr) || list[0]; const each = list.find(each => each.isLastDefaultAddr) || list[0];
uni.setStorageSync("warehousId", each.warehousId); uni.setStorageSync("warehousId", each.warehousId);
@ -216,7 +216,7 @@ async function getmyarea() {
// getBroadcast(); // getBroadcast();
getDFKDataLength(); getDFKDataLength();
if (!resp.data.login) {
if (!res.data.login) {
// FIXME: hiddenLogin.value = false; // FIXME: hiddenLogin.value = false;
} }
else { else {
@ -234,21 +234,20 @@ async function getmyarea() {
/** /**
* 获取广播 * 获取广播
*/ */
async function getBroadcast() {
const resp = await getBroadcastApi({
warehouseId: uni.getStorageSync("warehousId"),
});
if (resp.code !== "0") {
return;
}
const item = resp.data.findLast(item => item.status == 1);
// const nowTime = moment().format("YYYY-MM-DD HH:mm:ss");
if (JSON.stringify(resp.data) != "{}") {
const nowTime = moment().format("YYYY-MM-DD HH:mm:ss");
}
// TODO:
// broadcastText.value = item;
}
// async function getBroadcast() {
// const res = await getBroadcastApi({
// warehouseId: uni.getStorageSync("warehousId"),
// });
// if (res.code !== "0") {
// return;
// }
// const item = res.data.findLast(item => item.status == 1);
// if (JSON.stringify(res.data) != "{}") {
// const nowTime = moment().format("YYYY-MM-DD HH:mm:ss");
// }
// // TODO:
// // broadcastText.value = item;
// }
/** /**
* 查看公告列表 * 查看公告列表
*/ */
@ -715,7 +714,6 @@ onShow(() => {
<style lang="scss" scoped> <style lang="scss" scoped>
@import '../../uni.scss'; @import '../../uni.scss';
.main {}
.header-box { .header-box {
// position: fixed; // position: fixed;
// transition-all duration-300 pb-[15rpx] // transition-all duration-300 pb-[15rpx]

40
pages/home/honest.vue

@ -97,8 +97,8 @@ async function onSign() {
createTime: moment().format("YYYY-MM-DD"), createTime: moment().format("YYYY-MM-DD"),
image: sealImg.value, image: sealImg.value,
}; };
const resp = await addHonestApi(data);
if (resp && resp.code === "0") {
const res = await addHonestApi(data);
if (res && res.code === "0") {
uni.showToast({ uni.showToast({
title: "签订成功", title: "签订成功",
icon: "success", icon: "success",
@ -170,9 +170,9 @@ function onCheckPhone(e) {
*/ */
async function onSealImg(e) { async function onSealImg(e) {
if (e.detail.value) { if (e.detail.value) {
const resp = await sealImgApi({ companyName: e.detail.name });
if (resp && resp.code === "0") {
sealImg.value = resp.data;
const res = await sealImgApi({ companyName: e.detail.name });
if (res && res.code === "0") {
sealImg.value = res.data;
customerName.value = e.detail.value; customerName.value = e.detail.value;
} }
} }
@ -188,28 +188,28 @@ onReady(() => {
}); });
onShow(async () => { onShow(async () => {
const resp = await getUserInfoApi();
if (resp.code === "4") {
const res = await getUserInfoApi();
if (res.code === "4") {
isLogin.value = false; isLogin.value = false;
return; return;
} }
if (resp.code === "0") {
if (res.code === "0") {
isLogin.value = true; isLogin.value = true;
if (resp.data.company === undefined) {
if (res.data.company === undefined) {
isCompany.value = false; isCompany.value = false;
} }
else { else {
isCompany.value = true; isCompany.value = true;
companyId.value = resp.data.company.id;
companyName.value = resp.data.company.name;
const resp2 = await getHonestApi({ companyId: companyId.value });
if (resp2 && resp2.code === "0" && resp2.data.length) {
companyId.value = res.data.company.id;
companyName.value = res.data.company.name;
const res2 = await getHonestApi({ companyId: companyId.value });
if (res2 && res2.code === "0" && res2.data.length) {
disabled.value = true; disabled.value = true;
customerName.value = resp2.data[0].customerName;
managerPhone.value = resp2.data[0].managerPhone;
signature.value = resp2.data[0].signature;
date.value = resp2.data[0].createTime;
sealImg.value = resp2.data[0].image;
customerName.value = res2.data[0].customerName;
managerPhone.value = res2.data[0].managerPhone;
signature.value = res2.data[0].signature;
date.value = res2.data[0].createTime;
sealImg.value = res2.data[0].image;
} }
} }
} }
@ -242,7 +242,6 @@ onShow(async () => {
<text style="width:90rpx;font-size:30rpx;"> <text style="width:90rpx;font-size:30rpx;">
乙方 乙方
</text> </text>
<!-- <van-field v-model="customerNameSelf" style="width:calc(100% - 12.1rem)" disabled></van-field> -->
<input <input
v-model="customerNameSelf" v-model="customerNameSelf"
class="weui-input" class="weui-input"
@ -255,7 +254,8 @@ onShow(async () => {
</view> </view>
<view style="text-indent: 56rpx;"> <view style="text-indent: 56rpx;">
<view> <view>
甲乙双方为共同制止商业贿赂和不正当竞争行为维护各自及双方共同的合法权益充分体现公平公正廉洁诚信合作的精神保证甲乙双方商业合作关系的健康延续根据相关法律法规的规定经双方友好协商形成如下合意
甲乙双方为共同制止商业贿赂和不正当竞争行为维护各自及双方共同的合法权益充分体现公平公正廉洁诚信合作的精神
保证甲乙双方商业合作关系的健康延续根据相关法律法规的规定经双方友好协商形成如下合意
</view> </view>
<view> <view>
双方应自觉遵守有关法律法规规章制度及本协议项下关于公平交易廉洁自律反对不当利益输送的相关规定 双方应自觉遵守有关法律法规规章制度及本协议项下关于公平交易廉洁自律反对不当利益输送的相关规定

4
pages/index/index.vue

@ -34,8 +34,8 @@ function gotoHome() {
} }
onLoad(async () => { onLoad(async () => {
const resp = await getGuideImgsApi();
banner.value = resp.data;
const res = await getGuideImgsApi();
banner.value = res.data;
}); });
</script> </script>

133
pages/login/login.vue

@ -1,5 +1,5 @@
<script setup> <script setup>
import { onLoad, onShow } from "@dcloudio/uni-app";
import { onLoad } from "@dcloudio/uni-app";
import { ref } from "vue"; import { ref } from "vue";
import { import {
getmyareaApi, getmyareaApi,
@ -8,11 +8,11 @@ import {
loginApi, loginApi,
xcxWxLoginApi, xcxWxLoginApi,
} from "@/libs/api"; } from "@/libs/api";
import { gotoBack } from "@/libs/utils";
import { gotoBack, validates } from "@/libs/utils";
import config from "@/libs/utils/config"; import config from "@/libs/utils/config";
import { encryptData } from "@/libs/utils/crypto"; import { encryptData } from "@/libs/utils/crypto";
let appData = getApp().globalData;
const appData = getApp().globalData;
/** /**
* 判断小程序的API回调参数组件等是否在当前版本可用 * 判断小程序的API回调参数组件等是否在当前版本可用
*/ */
@ -68,15 +68,15 @@ function onGetUserProfile() {
// #ifdef MP-WEIXIN // #ifdef MP-WEIXIN
uni.getUserProfile({ uni.getUserProfile({
desc: "用于完善用户资料", // desc: "用于完善用户资料", //
success(resp) {
success(res) {
uni.showToast({ uni.showToast({
title: JSON.stringify(resp),
title: JSON.stringify(res),
icon: "none", icon: "none",
}); });
avatarUrl.value = resp.userInfo.avatarUrl;
nickName.value = resp.userInfo.nickName;
gender.value = resp.userInfo.gender;
avatarUrl.value = res.userInfo.avatarUrl;
nickName.value = res.userInfo.nickName;
gender.value = res.userInfo.gender;
wxLogin(); wxLogin();
}, },
fail(err) { fail(err) {
@ -102,10 +102,10 @@ function onGetUserProfile() {
*/ */
function wxLogin() { function wxLogin() {
uni.login({ uni.login({
async success(resp) {
const resp2 = await xcxWxLoginApi({ code: resp.code });
if (resp2.code === "0") {
openid.value = resp2.openid;
async success(res) {
const res2 = await xcxWxLoginApi({ code: res.code });
if (res2.code === "0") {
openid.value = res2.openid;
uni.setStorageSync("openid", openid.value); uni.setStorageSync("openid", openid.value);
getUserByXcxAPPOpenId({ openid: openid.value }); getUserByXcxAPPOpenId({ openid: openid.value });
} }
@ -127,23 +127,23 @@ async function getUserByXcxAPPOpenId(data) {
"version": "2.0", "version": "2.0",
}; };
uni.showLoading({ title: "登录中..." }); uni.showLoading({ title: "登录中..." });
const resp = await getUserByXcxAPPOpenIdApi(data);
const res = await getUserByXcxAPPOpenIdApi(data);
uni.hideLoading(); uni.hideLoading();
if (resp.code === "0") {
appData.header.session = resp.header.session;
appData.header["X-Header-Token"] = resp.header.session;
uni.setStorageSync("session", resp.header.session);
if (res.code === "0") {
appData.header.session = res.header.session;
appData.header["X-Header-Token"] = res.header.session;
uni.setStorageSync("session", res.header.session);
getmyarea(); getmyarea();
} }
else { else {
updateUserInfo(resp);
updateUserInfo(res);
} }
} }
async function getmyarea() { async function getmyarea() {
const resp = await getmyareaApi({ warehouseid: "", isEnabled: 1 });
if (resp.code === "0") {
const list = resp.data.list.sort((pre, cur) => Number(cur) - Number(pre));
const res = await getmyareaApi({ warehouseid: "", isEnabled: 1 });
if (res.code === "0") {
const list = res.data.list.sort((pre, cur) => Number(cur) - Number(pre));
// each isLastDefaultAddr // each isLastDefaultAddr
const each = list.find(each => each.isLastDefaultAddr) || list[0]; const each = list.find(each => each.isLastDefaultAddr) || list[0];
uni.setStorageSync("warehousId", each.warehousId); uni.setStorageSync("warehousId", each.warehousId);
@ -163,50 +163,33 @@ async function getmyarea() {
* 手机号登录 * 手机号登录
*/ */
async function onPhoneLogin() { async function onPhoneLogin() {
if (username.value === "") {
uni.showToast({
title: "请输入手机号",
icon: "none",
});
return;
}
if (password.value === "") {
uni.showToast({
title: "请输入密码",
icon: "none",
});
return;
}
if (!readed.value) {
uni.showToast({
title: "请先阅读并同意服务协议和隐私协议",
icon: "none",
});
const isPass = validates([
() => username.value === "" && "请输入手机号",
() => password.value === "" && "请输入密码",
() => !readed.value && "请先阅读并同意服务协议和隐私协议",
]);
if (!isPass)
return; return;
}
uni.showLoading({
title: "登录中...",
mask: true,
});
const resp = await loginApi({
uni.showLoading({ title: "登录中...", mask: true });
const res = await loginApi({
username: username.value, username: username.value,
password: password.value, password: password.value,
}); });
// TODO: 便 code === '0',
if (resp.code === "0") {
uni.setStorageSync("session", resp.data);
const setPhone = encryptData(username.value, config.SECRET_KEY);
uni.setStorageSync("phone", setPhone);
const setPassword = encryptData(password.value, config.SECRET_KEY);
uni.setStorageSync("password", setPassword);
gotoBack();
}
else {
uni.showToast({
title: resp.message,
icon: "none",
});
if (!validates(() => res.code !== "0" && res.message)) {
return;
} }
// TODO: 便 code === '0',
uni.setStorageSync("session", res.data);
const setPhone = encryptData(username.value, config.SECRET_KEY);
uni.setStorageSync("phone", setPhone);
const setPassword = encryptData(password.value, config.SECRET_KEY);
uni.setStorageSync("password", setPassword);
gotoBack();
uni.hideLoading(); uni.hideLoading();
} }
function onWechatLogin() {} function onWechatLogin() {}
@ -230,14 +213,14 @@ function onForgetPassword() { }
* 打开用户协议 * 打开用户协议
*/ */
async function onOpenUserAgreement() { async function onOpenUserAgreement() {
const resp = await getUserTreatyApi();
if (resp.code !== "0")
const res = await getUserTreatyApi();
if (res.code !== "0")
return; return;
uni.navigateTo({ uni.navigateTo({
url: "/pages/agreement/agreement", url: "/pages/agreement/agreement",
success(resp2) {
resp2.eventChannel.emit("serviceAgreement", {
html: resp.data.serviceAgreement,
success(res2) {
res2.eventChannel.emit("html", {
html: res.data.serviceAgreement,
title: "用户协议", title: "用户协议",
}); });
}, },
@ -248,14 +231,14 @@ async function onOpenUserAgreement() {
* 打开隐私协议 * 打开隐私协议
*/ */
async function onOpenPrivacyAgreement() { async function onOpenPrivacyAgreement() {
const resp = await getUserTreatyApi();
if (resp.code !== "0")
const res = await getUserTreatyApi();
if (res.code !== "0")
return; return;
uni.navigateTo({ uni.navigateTo({
url: "/pages/agreement/agreement", url: "/pages/agreement/agreement",
success(resp2) {
resp2.eventChannel.emit("privacyAgreement", {
html: resp.data.privacyAgreement,
success(res2) {
res2.eventChannel.emit("html", {
html: res.data.privacyAgreement,
title: "隐私协议", title: "隐私协议",
}); });
}, },
@ -267,10 +250,8 @@ onLoad(() => {
canIUseGetUserProfile.value = true; canIUseGetUserProfile.value = true;
} }
uni.getSystemInfo({ uni.getSystemInfo({
success(resp) {
if (resp.platform === "ios") {
isIos.value = true;
}
success(res) {
isIos.value = res.platform === "ios";
}, },
}); });
}); });
@ -287,7 +268,7 @@ onLoad(() => {
/> />
<!-- #ifdef MP-WEIXIN --> <!-- #ifdef MP-WEIXIN -->
<view style="paddingTop: 44px;">
<view style="padding-top: 44px;">
<view class="header"> <view class="header">
<image src="/static/logo.png" /> <image src="/static/logo.png" />
</view> </view>
@ -522,8 +503,6 @@ input {
padding: 70rpx 0rpx 20rpx; padding: 70rpx 0rpx 20rpx;
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
.password {
}
.forget { .forget {
color:#06CA64 color:#06CA64
} }

24
pages/personalInformation/personalInformation.vue

@ -274,8 +274,8 @@ function onGotoLogin() {
uni.showModal({ uni.showModal({
title: "提示", title: "提示",
content: "请先登录", content: "请先登录",
complete(resp) {
if (resp.confirm) {
complete(res) {
if (res.confirm) {
uni.navigateTo({ uni.navigateTo({
url: "/pages/login/login", url: "/pages/login/login",
}); });
@ -297,14 +297,14 @@ function onGetPosition() {}
* 获取用户信息 * 获取用户信息
*/ */
async function getUserInfo() { async function getUserInfo() {
const resp = await getUserInfoApi();
if (resp.code === "0") {
const res = await getUserInfoApi();
if (res.code === "0") {
isLogin.value = true; isLogin.value = true;
resp.data.walletMoney = (resp.data.walletMoney || 0).toFixed(2);
company.value = resp.data.company ? resp.data.company : undefined;
userInfo.value = resp.data;
res.data.walletMoney = (res.data.walletMoney || 0).toFixed(2);
company.value = res.data.company ? res.data.company : undefined;
userInfo.value = res.data;
} }
else if (resp.code === "4") {
else if (res.code === "4") {
// //
isLogin.value = false; isLogin.value = false;
userInfo.value = ""; userInfo.value = "";
@ -325,13 +325,13 @@ function getMyArea() { }
/** /**
* 获取仓库列表 * 获取仓库列表
*/ */
function getWarehouse() { }
// function getWarehouse() { }
async function getYesterdayOrder() { async function getYesterdayOrder() {
const resp = await yesterdayOrderApi();
if (resp.code === "0" && resp.data) {
const res = await yesterdayOrderApi();
if (res.code === "0" && res.data) {
position.value = true; position.value = true;
orderId.value = resp.data;
orderId.value = res.data;
} }
} }

2
store/index.js

@ -21,7 +21,7 @@ import { ref } from "vue";
export default defineStore("store", export default defineStore("store",
/** /**
* @returns {storeType}
* @returns {storeType} 返回 store 实例
*/ */
() => { () => {
/** /**

Loading…
Cancel
Save