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