封装分享功能

This commit is contained in:
2026-01-21 09:40:31 +08:00
parent a125995808
commit c60a2115ea
7 changed files with 1423 additions and 945 deletions

View File

@@ -136,6 +136,15 @@ export const getInviteCode = (data) => {
data: data, data: data,
}); });
}; };
export const autoGetInviteCode = (data) => {
return request({
url: prveUrl + "/user/distribution/autoGetInviteCode",
method: "get",
data: data,
});
};
// 获取配置 // 获取配置
export const getConfig = (data) => { export const getConfig = (data) => {

View File

@@ -1,6 +1,6 @@
// const debug = process.env.NODE_ENV == 'development' ? true : false; // const debug = process.env.NODE_ENV == 'development' ? true : false;
// const debug = false; // false线上 true本地 // const debug = false; // false线上 true本地
const debug = false; // false线上 true本地 const debug = true; // false线上 true本地
let baseUrl = '' let baseUrl = ''
let baseUrlwws = '' let baseUrlwws = ''

View File

@@ -5,7 +5,8 @@
<!-- 轮播图 --> <!-- 轮播图 -->
<swipers :carousel="hometoplist.bannerList"></swipers> <swipers :carousel="hometoplist.bannerList"></swipers>
<!-- 广告 --> <!-- 广告 -->
<advertisement :bannervo="hometoplist.freeBannerList" :itemStyle="advertisementStyle" ref="refbannervo"></advertisement> <advertisement :bannervo="hometoplist.freeBannerList" :itemStyle="advertisementStyle" ref="refbannervo">
</advertisement>
<!-- 金刚区 --> <!-- 金刚区 -->
<diamond :district="hometoplist.district"></diamond> <diamond :district="hometoplist.district"></diamond>
<!-- 今日上线 --> <!-- 今日上线 -->
@@ -134,10 +135,27 @@
<script setup> <script setup>
import CouponModal from '@/components/coupon-modal.vue'; import CouponModal from '@/components/coupon-modal.vue';
import { ref, computed, onMounted, reactive, onBeforeUnmount, watch, getCurrentInstance, nextTick } from 'vue'; import {
import { onLoad, onReady, onShow, onReachBottom, onPageScroll } from '@dcloudio/uni-app'; ref,
computed,
onMounted,
reactive,
onBeforeUnmount,
watch,
getCurrentInstance,
nextTick
} from 'vue';
import {
onLoad,
onReady,
onShow,
onReachBottom,
onPageScroll
} from '@dcloudio/uni-app';
// 获取全局属性 // 获取全局属性
const { proxy } = getCurrentInstance(); const {
proxy
} = getCurrentInstance();
import pageLoading from './components/pageLoading.vue'; import pageLoading from './components/pageLoading.vue';
import swipers from './components/swiper.vue'; //引入轮播 import swipers from './components/swiper.vue'; //引入轮播
import advertisement from './components/advertisement.vue'; //广告 import advertisement from './components/advertisement.vue'; //广告
@@ -147,11 +165,22 @@ import indexs from './indexs.vue';
import AreaSelect from './components/AreaSelect.vue'; //城市联动 import AreaSelect from './components/AreaSelect.vue'; //城市联动
import grouping from './components/grouping.vue'; //其他 import grouping from './components/grouping.vue'; //其他
import Nav from '@/components/indexnav.vue'; //导航栏 import Nav from '@/components/indexnav.vue'; //导航栏
import { APIhomehomePageUp, APIhome } from '@/common/api/index/index.js'; import {
import { APIgeocodelocation } from '@/common/api/api.js'; APIhomehomePageUp,
import { useNavbarStore } from '@/stores/navbarStore'; APIhome
import { productStore } from '@/stores/user.js'; } from '@/common/api/index/index.js';
import { getUnReadCountReq } from '../../common/api/account/message'; import {
APIgeocodelocation
} from '@/common/api/api.js';
import {
useNavbarStore
} from '@/stores/navbarStore';
import {
productStore
} from '@/stores/user.js';
import {
getUnReadCountReq
} from '../../common/api/account/message';
const store = useNavbarStore(); const store = useNavbarStore();
const storeuser = productStore(); const storeuser = productStore();
store.updateNavbarConfig({ store.updateNavbarConfig({
@@ -316,7 +345,8 @@ const viewHistory = async (item, index) => {
} }
// 是否有弹出层 // 是否有弹出层
if (item.isChild) { if (item.isChild) {
showproductlist.value = showproductlist.value ? (viewHistoryindex.value == index ? false : true) : !showproductlist.value; showproductlist.value = showproductlist.value ? (viewHistoryindex.value == index ? false : true) : !
showproductlist.value;
} }
viewHistoryindex.value = index; viewHistoryindex.value = index;
}; };
@@ -327,18 +357,35 @@ onPageScroll((res) => {
}); });
const indexsRef = ref(null); const indexsRef = ref(null);
const shopId = ref(null)
const shopInfo = ref(null)
onShow(async () => { onShow(async () => {
if (!storeuser.isHasLogin) {
await handleMixinOnLoad(options)
console.log('shopInfo', uni.cache.get('shopInfo'));
console.log('【页面】开始处理自身业务逻辑');
setTimeout(() => {
showPageLoading.value = false;
getUnReadMsgCount();
}, 800);
onPageShow()
} else {
onPageShow()
}
});
async function onPageShow() {
try { try {
await storeuser.getLocation(); await storeuser.getLocation();
proxy.$isResolve(); proxy.$isResolve();
const shopId = uni.cache.get('shopId'); shopId.value = uni.cache.get('shopId');
if (shopId) { if (shopId.value) {
indexsRef.value.updateData(); indexsRef.value.updateData();
} }
} catch (error) {} } catch (error) {}
await proxy.$onLaunched; await proxy.$onLaunched;
if (uni.cache.get('shopId')) { if (shopId.value) {
showindex.value = 'shopIndex'; showindex.value = 'shopIndex';
await storeuser.actionsproductqueryProduct(); await storeuser.actionsproductqueryProduct();
await nextTick(); await nextTick();
@@ -349,7 +396,9 @@ onShow(async () => {
init_fn(); init_fn();
// 获取初始定位高度 // 获取初始定位高度
} }
});
shopInfo.value = uni.cache.get('shopInfo');
}
const showPageLoading = ref(true); const showPageLoading = ref(true);
@@ -369,18 +418,52 @@ const getUnReadMsgCount = async () => {
} }
} }
onMounted(async () => {
setTimeout(() => {
showPageLoading.value = false;
getUnReadMsgCount();
}, 800);
});
onReachBottom(() => { onReachBottom(() => {
onLoadhome(); onLoadhome();
}); });
import {
shareMixin,
handleMixinOnLoad
} from '@/utils/share.js'
watch(() => shopId.value, (newval) => {
if (newval) {
uni.showShareMenu({
withShareTicket: true, // 可选:是否返回分享票据
menus: ['shareAppMessage', 'shareTimeline'] // 显示「分享好友」和「分享朋友圈」
});
} else {
uni.hideShareMenu();
}
}, {
immediate: true
})
defineOptions({
mixins: [shareMixin],
});
const options = reactive({})
onLoad(async (opt) => {
Object.assign(options, opt)
// await handleMixinOnLoad(options)
// console.log('shopInfo', uni.cache.get('shopInfo'));
// console.log('【页面】开始处理自身业务逻辑');
// setTimeout(() => {
// showPageLoading.value = false;
// getUnReadMsgCount();
// }, 800);
})
// 页面离开时清除定时器 // 页面离开时清除定时器
// onBeforeUnmount(() => { // onBeforeUnmount(() => {
// if (refbannervo.value) { // if (refbannervo.value) {

View File

@@ -2,9 +2,11 @@
<view class="content min-page bg-f7"> <view class="content min-page bg-f7">
<view class="contentbox"> <view class="contentbox">
<template v-if="shopExtend.length"> <template v-if="shopExtend.length">
<image class="bg" :src="shopExtend[0].value" mode="aspectFill" v-if="!isJsonArrayString(shopExtend[0].value)"></image> <image class="bg" :src="shopExtend[0].value" mode="aspectFill"
v-if="!isJsonArrayString(shopExtend[0].value)"></image>
<swiper class="swiper" autoplay circular v-else> <swiper class="swiper" autoplay circular v-else>
<swiper-item class="swiper-item" v-for="(item, index) in JSON.parse(shopExtend[0].value)" :key="index"> <swiper-item class="swiper-item" v-for="(item, index) in JSON.parse(shopExtend[0].value)"
:key="index">
<image class="swiper-bg" :src="item"></image> <image class="swiper-bg" :src="item"></image>
</swiper-item> </swiper-item>
</swiper> </swiper>
@@ -119,10 +121,23 @@
<script setup> <script setup>
import attractPopup from '@/components/attract-popup.vue'; import attractPopup from '@/components/attract-popup.vue';
import { homeData } from '@/common/api/market/index.js'; import {
import { getMemberConfig, getRechargeConfig } from '@/common/api/index/index.js'; homeData
import { ref, reactive, defineProps, defineEmits, onMounted } from 'vue'; } from '@/common/api/market/index.js';
import { isJsonArrayString } from '@/utils/util.js'; import {
getMemberConfig,
getRechargeConfig
} from '@/common/api/index/index.js';
import {
ref,
reactive,
defineProps,
defineEmits,
onMounted
} from 'vue';
import {
isJsonArrayString
} from '@/utils/util.js';
const attractPopupRef = ref(null); const attractPopupRef = ref(null);
@@ -165,8 +180,12 @@ function toIntegralMall() {
}); });
} }
import { productStore } from '@/stores/user.js'; import {
import { onShow } from '@dcloudio/uni-app'; productStore
} from '@/stores/user.js';
import {
onShow
} from '@dcloudio/uni-app';
// 显示弹窗 // 显示弹窗
const popupShow = ref(false); const popupShow = ref(false);
@@ -295,6 +314,9 @@ function updateData() {
defineExpose({ defineExpose({
updateData updateData
}); });
</script> </script>
<style scoped lang="scss"> <style scoped lang="scss">
@@ -523,8 +545,7 @@ page {
background: #ededed; background: #ededed;
} }
.takeout { .takeout {}
}
} }
&.layout1 { &.layout1 {

View File

@@ -749,7 +749,7 @@
useCartStore useCartStore
} from '@/stores/order.js'; } from '@/stores/order.js';
import { import {
computed, provide computed, provide, reactive
} from 'vue'; } from 'vue';
const cartStore = useCartStore(); const cartStore = useCartStore();
/** /**
@@ -2437,27 +2437,50 @@
}); });
} }
import {
shareMixin,
handleMixinOnLoad,returnQuery
} from '@/utils/share.js'
defineOptions({
mixins: [shareMixin],
});
onShareAppMessage((res)=>{
let query=returnQuery()
query+='&type=beforehand'
return {
...res,
...query,
path: '/pages/product/index' + '?' + query,
query,
}
})
const pageOptions=reactive({})
onLoad(async (e) => { onLoad(async (e) => {
Object.assign(pageOptions,e)
if (e.type) { if (e.type) {
orderType.value = e.type; orderType.value = e.type;
} }
//获取用户信息 await handleMixinOnLoad(e)
const userInfo = await APIshopUserInfo({ const userInfo= userStore.userInfo
shopId: uni.cache.get('shopId') const shopInfoRes=userStore.shopInfo
}) // //获取用户信息
//获取店铺信息 // const userInfo = await APIshopUserInfo({
const shopInfoRes = await APIusershopInfodetail({ // shopId: uni.cache.get('shopId')
shopId: uni.cache.get('shopId') // })
}); // //获取店铺信息
// const shopInfoRes = await APIusershopInfodetail({
// shopId: uni.cache.get('shopId')
// });
if (shopInfoRes && shopInfoRes.shopInfo) { if (shopInfoRes && shopInfoRes.shopInfo) {
Object.assign(shopInfo, shopInfoRes.shopInfo); Object.assign(shopInfo, shopInfoRes.shopInfo);
uni.cache.set('shopInfo', shopInfoRes.shopInfo)
} }
if (userInfo && typeof userInfo === 'object') { if (userInfo && typeof userInfo === 'object') {
shopUserInfo.value = userInfo shopUserInfo.value = userInfo
uni.cache.set('shopUserInfo', userInfo)
} }
await productqueryProduct(); await productqueryProduct();

View File

@@ -110,12 +110,90 @@ export const productStore = defineStore("product", {
latitude: "", latitude: "",
longitude: "", longitude: "",
}, },
token: "",
miniAppOpenId: "",
userInfo: "",
shopId: uni.cache.get('shopId') || '',
shopInfo: { shopInfo: {
shopId: "", shopId: "",
isOrderFence: 0, isOrderFence: 0,
id: '',
}, },
shopUserInfo:{
},
isHasLogin:false
}), }),
actions: { actions: {
actionslogin() {
return new Promise(async (resolve, reject) => {
// #ifdef MP-WEIXIN
uni.login({
provider: "weixin",
success: (data) => {
// 微信小程序环境
uni.getUserInfo({
provider: "weixin",
success: async (infoRes) => {
let res = await APIuserlogin({
code: data.code, //临时登录凭证
rawData: infoRes.rawData,
source: "wechat",
});
console.log('APIuserlogin', res);
if (res) {
this.token = res.token;
this.isHasLogin=true
this.miniAppOpenId = res.userInfo
.miniAppOpenId;
this.userInfo = res.userInfo;
uni.cache.set("token", res.token);
uni.cache.set("userInfo", res.userInfo);
uni.cache.set("followIndex", res
.followIndex || "");
}
resolve(true);
},
fail: (err) => {
reject(false);
},
});
},
});
// #endif
// #ifdef MP-ALIPAY
my.getAuthCode({
scopes: "auth_base",
success: async (data) => {
// 支付宝小程序环境
// my.getAuthUserInfo({
// success: async (infoRes) => {
let res = await APIuserlogin({
code: data.authCode, //临时登录凭证
// rawData: JSON.stringify(infoRes),
source: "alipay",
});
if (res) {
this.isHasLogin=true
this.token = res.token;
this.miniAppOpenId = res.userInfo.miniAppOpenId;
this.userInfo = res.userInfo;
uni.cache.set("token", res.token);
uni.cache.set("openId", res.userInfo.alipayOpenId);
uni.cache.set("userInfo", res.userInfo);
resolve(true);
}
},
fail: () => {
reject(false);
},
});
// #endif
// #ifdef H5
resolve(true)
// #endif
});
},
getLocation() { getLocation() {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
console.log("获取经纬度"); console.log("获取经纬度");
@@ -448,19 +526,41 @@ export const productStore = defineStore("product", {
// 通过shopId 获取店铺会员信息 // 通过shopId 获取店铺会员信息
actionsproductqueryProduct() { actionsproductqueryProduct() {
console.log('actionsproductqueryProduct:token',uni.cache.get('token'));
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
try { try {
let res = await APIshopUserInfo(); let res = await APIshopUserInfo();
if(res&& typeof res === 'object'){
this.shopUserInfo=res;
uni.cache.set("shopUserInfo", res); uni.cache.set("shopUserInfo", res);
uni.cache.set("orderVIP", res); uni.cache.set("orderVIP", res);
uni.cache.set("ordershopUserInfo", res.shopInfo); uni.cache.set("ordershopUserInfo", res.shopInfo);
resolve(res); resolve(res);
}else{
reject(false);
}
} catch (e) { } catch (e) {
reject(false); reject(false);
} }
}); });
}, },
async pageOnload() {
//登录
await this.actionslogin()
//获取会员信息
await this.actionsproductqueryProduct()
//获取店铺信息
await this.getShopInfo()
},
async getShopInfo(shopId) {
const shopRes = await APIusershopInfodetail({
shopId: this.shopId || shopId,
});
this.shopInfo = shopRes.shopInfo;
uni.cache.set("shopInfo", shopRes.shopInfo);
},
// 用户信息获取 // 用户信息获取
actionsAPIuser() { actionsAPIuser() {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {

View File

@@ -1,7 +1,15 @@
import { import {
autoBindInviteUser autoBindInviteUser,
autoGetInviteCode
} from '@/common/api/market/distribution.js' } from '@/common/api/market/distribution.js'
import {
APIshopUserInfo,
APIusershopInfodetail
} from '@/common/api/member.js'
import {
productStore
} from '@/stores/user.js';
const accountStore = productStore();
const accountInfo = wx.getAccountInfoSync(); const accountInfo = wx.getAccountInfoSync();
export const envVersion = accountInfo.miniProgram.envVersion; export const envVersion = accountInfo.miniProgram.envVersion;
let type = 3; let type = 3;
@@ -53,3 +61,237 @@ export function wxShare(par) {
type type
} }
} }
export async function returnQuery(query) {
const shopId = uni.cache.get('shopId')
const shopUserInfo = uni.cache.get('shopUserInfo')
const shopInfo = uni.cache.get('shopInfo')
const inviteCode = await autoGetInviteCode({
shopId: shopId,
shopUserId: shopUserInfo.id
})
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
const currentPath = currentPage.route;
const currentOptions = currentPage.options;
let sharePath = `/${currentPath}`;
const queryJson = {
inviteCode: (inviteCode && inviteCode !== true) ? inviteCode : null,
shopId,
shopUserId: shopUserInfo.id,
...query
}
for (const key in currentOptions) {
if (currentOptions.hasOwnProperty(key)) {
queryJson[key] = encodeURIComponent(currentOptions[key])
}
}
queryJson.shopId = shopId
queryJson.inviteCode = (inviteCode && inviteCode !== true) ? inviteCode : null
queryJson.shopUserId = shopUserInfo.id
let result = ''
for (let key in queryJson) {
if (queryJson[key]) {
if (result === '') {
result += `${key}=${queryJson[key]}`
} else {
result += `&${key}=${queryJson[key]}`
}
}
}
return result
}
function parseQueryString(queryString) {
const queryParams = queryString.split("&").map((param) => param.split("="));
const params = {};
for (const [key, value] of queryParams) {
params[key] = value;
}
return params;
}
/**
* 混入的 onLoad 核心逻辑(抽成独立函数)
* @param {Object} opt - 页面 onLoad 接收的参数
* @param {Object} vm - 组件实例this
*/
export async function handleMixinOnLoad(opt, vm) {
console.log('onLoad');
const options = {}
if (opt.q) {
const q = decodeURIComponent(opt.q);
const params = parseQueryString(q.split("?")[1]);
Object.assign(options, params);
} else {
Object.assign(options, opt);
}
console.log('options', options);
if (options.shopId) {
uni.cache.set('shopId', options.shopId)
accountStore.shopId = options.shopId
await accountStore.pageOnload()
}
uni.setStorageSync('loadFinsh', true)
// const shopId = uni.cache.get('shopId')
// const shopUserInfo = uni.cache.get('shopUserInfo')
// const shopInfo = uni.cache.get('shopInfo')
// const inviteCode = await autoGetInviteCode({
// shopId: shopId,
// shopUserId: shopUserInfo.id
// })
if (options.inviteCode) {
bindInvite(options)
}
}
// utils/share.js
export const shareMixin = {
// async onLoad(opt) {
// console.log('onLoad');
// const options = {}
// if (opt.q) {
// const q = decodeURIComponent(opt.q);
// const params = parseQueryString(q.split("?")[1]);
// Object.assign(options, params);
// } else {
// Object.assign(options, opt);
// }
// console.log('options', options);
// if (options.shopId) {
// uni.cache.set('shopId', options.shopId)
// }
// const shopId = uni.cache.get('shopId')
// const shopUserInfo = uni.cache.get('shopUserInfo')
// const shopInfo = uni.cache.get('shopInfo')
// const inviteCode = await autoGetInviteCode({
// shopId: shopId,
// shopUserId: shopUserInfo.id
// })
// uni.setStorageSync('loadFinsh',true)
// if (options.inviteCode) {
// bindInvite(options)
// }
// },
async onShareAppMessage(res) {
// const shopId = uni.cache.get('shopId')
// const shopUserInfo = uni.cache.get('shopUserInfo')
const shopInfo = uni.cache.get('shopInfo')
// const inviteCode = await autoGetInviteCode({
// shopId: shopId,
// shopUserId: shopUserInfo.id
// })
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
const currentPath = currentPage.route;
const currentOptions = currentPage.options;
let sharePath = `/${currentPath}`;
// const queryJson = {
// inviteCode: (inviteCode && inviteCode !== true) ? inviteCode : null,
// shopId,
// shopUserId: shopUserInfo.id,
// }
// for (const key in currentOptions) {
// if (currentOptions.hasOwnProperty(key)) {
// queryJson[key] = encodeURIComponent(currentOptions[key])
// }
// }
// queryJson.shopId = shopId
// queryJson.inviteCode = (inviteCode && inviteCode !== true) ? inviteCode : null
// queryJson.shopUserId = shopUserInfo.id
const query = returnQuery()
// 全局默认配置(可被页面覆盖)
const defaultShareConfig = {
title: shopInfo.shopName,
path: sharePath + '?' + query,
imageUrl: shopInfo.logo,
query,
// desc: '描述',
success: (res) => {
console.log('分享好友成功', res);
// 可加埋点等统一逻辑
},
fail: (err) => {
console.error('分享好友失败', err);
}
};
// 页面自定义配置覆盖全局
const pageShareConfig = this.$options.shareConfig || {};
console.log('mixIn onShareAppMessage', {
...defaultShareConfig,
...pageShareConfig
})
return {
...defaultShareConfig,
...pageShareConfig
};
},
async onShareTimeline() {
// const shopId = uni.cache.get('shopId')
// const shopUserInfo = uni.cache.get('shopUserInfo')
const shopInfo = uni.cache.get('shopInfo')
// const inviteCode = await autoGetInviteCode({
// shopId: shopId,
// shopUserId: shopUserInfo.id
// })
const pages = getCurrentPages();
const currentPage = pages[pages.length - 1];
const currentPath = currentPage.route;
const currentOptions = currentPage.options;
let sharePath = `/${currentPath}`;
// const queryJson = {
// inviteCode: (inviteCode && inviteCode !== true) ? inviteCode : null,
// shopId,
// shopUserId: shopUserInfo.id,
// }
// for (const key in currentOptions) {
// if (currentOptions.hasOwnProperty(key)) {
// queryJson[key] = encodeURIComponent(currentOptions[key])
// }
// }
// queryJson.shopId = shopId
// queryJson.inviteCode = (inviteCode && inviteCode !== true) ? inviteCode : null
// queryJson.shopUserId = shopUserInfo.id
const query = returnQuery()
const defaultTimelineConfig = {
title: shopInfo.shopName,
path: sharePath + '?' + query,
imageUrl: shopInfo.logo,
query,
};
const pageTimelineConfig = this.$options.shareTimelineConfig || {};
return {
...defaultTimelineConfig,
...pageTimelineConfig
};
}
};