文件
yjyf/yjyf-app/utils/share.js
MiAn fafddceaf2 feat: 新增发票抬头、晒单、钱包日志等模型及后台管理功能
- 新增 invoice_title、showcase、wallet_log 模型及对应语言包
- 新增后台控制器、视图及搜索字段配置
- 修复服务类目删除保护逻辑
- 优化后台登录页面文案及样式
- 新增前端角色切换逻辑及页面拦截
- 新增 SVG 图标及样式变量
- 修复接口权限及下拉框默认值问题
2026-11-11 17:02:35 +08:00

297 行
8.6 KiB
JavaScript

此文件含有模棱两可的 Unicode 字符

此文件含有可能会与其他字符混淆的 Unicode 字符。 如果您是想特意这样的,可以安全地忽略该警告。 使用 Escape 按钮显示他们。

/**
* 优匠优服 · 小程序分享好友 (onShareAppMessage) 与分享朋友圈 (onShareTimeline) 统一引擎
*/
import { getCurrentInstance } from 'vue';
import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app';
import { getUser } from './request.js';
export const DEFAULT_SHARE_TITLE = '优匠优服 · 专业师傅极速上门安装维修';
export const DEFAULT_SHARE_PATH = '/pages/index/index';
export const DEFAULT_SHARE_IMAGE = '/static/brand-logo.png';
// 允许外部好友直接打开的公开/半公开页面路由白名单
const PUBLIC_SHARE_ROUTES = [
'pages/index/index',
'pages/category/category',
'pages/service/list',
'pages/service/detail',
'pages/order/case',
'pages/master/detail',
'pages/master/hall',
'pages/master/apply',
'pages/coupon/coupon'
];
// 各路由默认分享文案
const ROUTE_SHARE_TITLES = {
'pages/index/index': '优匠优服 · 专业家居安装维修平台,实名师傅极速上门',
'pages/category/category': '优匠优服 · 全品类家居安装与维修服务,明码标价',
'pages/service/list': '优匠优服 · 严选专业师傅上门安装维修服务',
'pages/service/detail': '优匠优服 · 标准化上门安装维修,验收满意再付款',
'pages/order/case': '优匠优服 · 真实完工实况与业主口碑评价',
'pages/master/detail': '【同城工单派发】优匠优服新工单,认证师傅快来接单',
'pages/master/hall': '优匠优服 · 师傅接单大厅,海量同城好单实时派发',
'pages/master/apply': '优匠优服师傅招募 · 实名技能认证,海量同城工单随时接',
'pages/coupon/coupon': '优匠优服 · 领券中心,预约安装维修立享优惠'
};
/**
* 将对象参数序列化为 URL query 字符串
*/
export function stringifyShareQuery(params = {}) {
if (!params || typeof params !== 'object') return '';
const parts = [];
Object.keys(params).forEach((key) => {
const val = params[key];
if (val !== undefined && val !== null && val !== '') {
parts.push(`${encodeURIComponent(key)}=${encodeURIComponent(String(val))}`);
}
});
return parts.join('&');
}
/**
* 解析带参数的路径为 { route, queryStr, queryObj }
*/
export function parseSharePath(fullPath = '') {
const clean = String(fullPath || '').trim() || DEFAULT_SHARE_PATH;
const normalized = clean.startsWith('/') ? clean : '/' + clean;
const qIndex = normalized.indexOf('?');
if (qIndex === -1) {
return {
route: normalized.replace(/^\/+/, ''),
path: normalized,
queryStr: ''
};
}
const pathOnly = normalized.slice(0, qIndex);
const queryStr = normalized.slice(qIndex + 1);
return {
route: pathOnly.replace(/^\/+/, ''),
path: pathOnly,
queryStr
};
}
/**
* 获取当前活跃页面的路由与参数
*/
function getCurrentPageMeta() {
try {
const pages = typeof getCurrentPages === 'function' ? getCurrentPages() : [];
if (pages && pages.length) {
const cur = pages[pages.length - 1];
const route = cur.route || (cur.$page && cur.$page.route) || 'pages/index/index';
const options = cur.options || (cur.$page && cur.$page.options) || {};
return { route: route.replace(/^\/+/, ''), options, pageInstance: cur };
}
} catch (e) {}
return { route: 'pages/index/index', options: {}, pageInstance: null };
}
/**
* 附加分享人标识(如已登录则携带 share_uid 便于后续溯源)
*/
function appendSharerTrack(queryStr = '') {
try {
const user = getUser();
if (user && user.id) {
if (!/(^|&)share_uid=/.test(queryStr)) {
return queryStr ? `${queryStr}&share_uid=${user.id}` : `share_uid=${user.id}`;
}
}
} catch (e) {}
return queryStr;
}
/**
* 根据当前页面自动推断默认分享数据
*/
export function buildDefaultShareData(vm) {
const { route, options } = getCurrentPageMeta();
const isPublic = PUBLIC_SHARE_ROUTES.includes(route);
let title = ROUTE_SHARE_TITLES[route] || DEFAULT_SHARE_TITLE;
let targetRoute = isPublic ? `/${route}` : DEFAULT_SHARE_PATH;
let queryStr = isPublic ? stringifyShareQuery(options) : '';
let imageUrl = '';
// 首页若处于非首页 Tab(如订单/消息/我的),分享路径收敛回首页 Tab 0
if (route === 'pages/index/index') {
queryStr = '';
}
// 服务列表页动态带入分类名或搜索词
if (route === 'pages/service/list') {
const catName = options.cat_name ? decodeURIComponent(options.cat_name) : '';
const kw = options.keyword ? decodeURIComponent(options.keyword) : '';
if (catName) {
title = `优匠优服 · ${catName}专业上门安装与维修`;
} else if (kw) {
title = `优匠优服 · 「${kw}」上门安装维修服务`;
}
}
// 读取页面通过 useShare 挂载的实时自定义数据
const customGetter = vm && vm.$ && typeof vm.$.__yjyfShareGetter === 'function'
? vm.$.__yjyfShareGetter
: null;
if (customGetter) {
try {
const custom = customGetter() || {};
if (custom.title) title = custom.title;
if (custom.imageUrl) imageUrl = custom.imageUrl;
if (custom.path) {
const parsed = parseSharePath(custom.path);
targetRoute = parsed.path;
queryStr = parsed.queryStr;
}
if (custom.query !== undefined) {
queryStr = typeof custom.query === 'object'
? stringifyShareQuery(custom.query)
: String(custom.query || '').replace(/^\?/, '');
}
} catch (e) {}
}
const trackedQuery = appendSharerTrack(queryStr);
const finalPath = trackedQuery ? `${targetRoute}?${trackedQuery}` : targetRoute;
return {
title: title || DEFAULT_SHARE_TITLE,
path: finalPath || DEFAULT_SHARE_PATH,
query: trackedQuery,
imageUrl: imageUrl || ''
};
}
/**
* 页面级组合式分享钩子(在 <script setup> 中调用)
* @param {Function|Object} getterOrConfig 返回 { title, path, query, imageUrl } 的函数或配置对象
*/
export function useShare(getterOrConfig) {
const instance = getCurrentInstance();
const getter = typeof getterOrConfig === 'function'
? getterOrConfig
: () => (getterOrConfig || {});
if (instance) {
instance.__yjyfShareGetter = getter;
}
// 显式调用 uni-app 生命周期钩子,触发编译器生成页面级 __runtimeHooks
onShareAppMessage((res) => {
const proxy = instance && instance.proxy ? instance.proxy : null;
const data = buildDefaultShareData(proxy);
const out = {
title: data.title,
path: data.path
};
if (data.imageUrl) {
out.imageUrl = data.imageUrl;
}
return out;
});
onShareTimeline(() => {
const proxy = instance && instance.proxy ? instance.proxy : null;
const data = buildDefaultShareData(proxy);
const out = {
title: data.title,
query: data.query || ''
};
if (data.imageUrl) {
out.imageUrl = data.imageUrl;
}
return out;
});
}
/**
* H5 / App 端点击分享按钮时的兼容处理(微信小程序端使用 <button open-type="share">)
*/
export function triggerCustomShare(customInfo = {}) {
const title = customInfo.title || DEFAULT_SHARE_TITLE;
const path = customInfo.path || DEFAULT_SHARE_PATH;
// #ifdef H5
const fullUrl = typeof window !== 'undefined' && window.location
? `${window.location.origin}/#${path.startsWith('/') ? path : '/' + path}`
: path;
if (typeof navigator !== 'undefined' && typeof navigator.share === 'function') {
navigator.share({
title: title,
text: title,
url: fullUrl
}).catch(() => {});
return;
}
uni.setClipboardData({
data: `${title} ${fullUrl}`,
success: () => {
uni.showToast({ title: '已复制分享链接,快去发给好友吧', icon: 'none' });
}
});
// #endif
// #ifndef H5
uni.setClipboardData({
data: `${title}`,
success: () => {
uni.showToast({ title: '请点击右上角“...”转发给好友或分享朋友圈', icon: 'none' });
}
});
// #endif
}
/**
* 全局分享 Mixin:确保小程序所有页面自动开启右上角“转发给朋友”与“分享到朋友圈”
*/
export default {
onLoad() {
// #ifdef MP-WEIXIN
if (typeof uni.showShareMenu === 'function') {
uni.showShareMenu({
withShareTicket: true,
menus: ['shareAppMessage', 'shareTimeline'],
fail: () => {}
});
}
// #endif
},
onShow() {
// #ifdef MP-WEIXIN
if (typeof uni.showShareMenu === 'function') {
uni.showShareMenu({
withShareTicket: true,
menus: ['shareAppMessage', 'shareTimeline'],
fail: () => {}
});
}
// #endif
},
onShareAppMessage(res) {
const data = buildDefaultShareData(this);
const out = {
title: data.title,
path: data.path
};
if (data.imageUrl) {
out.imageUrl = data.imageUrl;
}
return out;
},
onShareTimeline() {
const data = buildDefaultShareData(this);
const out = {
title: data.title,
query: data.query || ''
};
if (data.imageUrl) {
out.imageUrl = data.imageUrl;
}
return out;
}
};