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)
相关推荐
Jul1en_6 分钟前
Claude 迁移 Codex 工作流迁移与更新
java·服务器·前端·后端·ai编程
Heo8 分钟前
14_React 中的更新队列 updateQueue
前端·javascript·面试
前端 贾公子14 分钟前
解决浏览器端 globalThis is not defined 报错
前端·javascript·vue.js
宁雨桥17 分钟前
前端与AI结合实战分享
前端·人工智能
之歆36 分钟前
DAY12_CSS3选择器全攻略 + 盒子新特性完全指南(下)
前端·javascript·css3
kyriewen1138 分钟前
代码写成一锅粥?3个设计模式让你的项目“起死回生”
开发语言·前端·javascript·设计模式·ecmascript
光影少年43 分钟前
react函数组件、类组件、纯组件、受控/非受控组件
前端·react.js·掘金·金石计划
程序员包打听43 分钟前
MoonBit 是什么?给第一次听说这门语言的你
前端·后端
Rkgua1 小时前
CSS动画效果
前端·css
Rkgua1 小时前
Flexbox 与 Grid 布局
前端·css