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)
相关推荐
Csvn7 小时前
WASM
前端
修己xj8 小时前
我用 AI 给自己写了一个 Markdown 编辑器,然后把它开源了
前端
FRing039 小时前
vue2干货总结2(v-bind、v-for、v-model、指令修饰符、v-bind操作class和style)
开发语言·前端·vue.js·vue2
幸运小猿9 小时前
模拟慢上传-处理超时重试image 丢失线上问题
前端·javascript·html
moshuying10 小时前
网购能买Token了!
前端
h_654321011 小时前
echarts实现柱状图加一条横线
前端·echarts
风骏时光牛马11 小时前
生成一个后端标题,只需要一个标题,不需要其他的任何文本。
前端
子非鱼@Itfuture11 小时前
关于前后端联调中登录状态/登录信息失效?
java·前端
郭小李11 小时前
openFeign入门
java·开发语言·前端
馒头不想说话11 小时前
AI当运营,帮你省人力
前端