UniApp,在微信小程序下,使用Hook来完成分享

在微信小程序中,如果多个页面都有分享的配置,大部分会考虑将分享的代码封装一下然后各个页面按需调用,一般人写法会是这样

typescript 复制代码
// share.ts
import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'

const home = '/pages/home'

export interface ShareOptions {
    title?: string
    path?: string
    imageUrl?: string
    query?: AnyObject
}

export function useMpShare() {
    function share(
        optionsFn: (() => ShareOptions) | ShareOptions = () => ({
            title: '小程序名称',
            path: '',
            imageUrl: '',
            query: {},
        })
    ) {
        onShareAppMessage(() => {
            const options = typeof optionsFn === 'function' ? optionsFn() : optionsFn
            return buildOptions(options)
        })
    }

    return { share }
}

// home.vue
import { useMpShare } from '@/hooks/use-share'
const { share }  = useMpShare()
share()

正常看这样确实没问题,但是上真机测试后,发现,传入的自定义title不起作用。查阅文档和测试后发现,需要做以下改动

typescript 复制代码
// share.ts
import { onShareAppMessage, onShareTimeline } from '@dcloudio/uni-app'

const home = '/pages/home'

export interface ShareOptions {
    title?: string
    path?: string
    imageUrl?: string
    query?: AnyObject
}

export function useMpShare() {
    function share(
        optionsFn: (() => ShareOptions) | ShareOptions = () => ({
            title: '小程序名称',
            path: '',
            imageUrl: '',
            query: {},
        })
    ) {
        onShareAppMessage(() => {
            const options = typeof optionsFn === 'function' ? optionsFn() : optionsFn
            return buildOptions(options)
        })
    }

    return { onShareAppMessage: share } // 将暴露出去的函数名改为 onShareAppMessage
}

// home.vue
import { useMpShare } from '@/hooks/use-share'
const { onShareAppMessage }  = useMpShare()
onShareAppMessage({ title: '此页面的title' })

另外,参数的传入如果是个动态值也有要求

javascript 复制代码
// home.vue
import { useMpShare } from '@/hooks/use-share'
const { onShareAppMessage }  = useMpShare()
const options = { title: '如果title需要动态赋值' }
onShareAppMessage(() => options) // onShareAppMessage 必须在根上进行调用,不能在请求完成后调用

api.fetchData().then((r) => options.title = r.title)
相关推荐
IT_陈寒15 小时前
Redis 性能翻倍的 7 个冷门技巧,第 5 个大多数人都不知道!
前端·人工智能·后端
mCell1 天前
GSAP ScrollTrigger 详解
前端·javascript·动效
gnip1 天前
Node.js 子进程:child_process
前端·javascript
excel1 天前
为什么在 Three.js 中平面能产生“起伏效果”?
前端
excel1 天前
Node.js 断言与测试框架示例对比
前端
天蓝色的鱼鱼1 天前
前端开发者的组件设计之痛:为什么我的组件总是难以维护?
前端·react.js
codingandsleeping1 天前
使用orval自动拉取swagger文档并生成ts接口
前端·javascript
石金龙1 天前
[译] Composition in CSS
前端·css
白水清风1 天前
微前端学习记录(qiankun、wujie、micro-app)
前端·javascript·前端工程化
Ticnix1 天前
函数封装实现Echarts多表渲染/叠加渲染
前端·echarts