// hooks文件
import { ref, onMounted } from 'vue'
import { onLoad, onShareTimeline, onShareAppMessage } from '@dcloudio/uni-app'
export default function useShare(query = {}) {
onShareTimeline(() => {
console.log('share onShareTimeline')
return query
})
onShareAppMessage(() => {
console.log('share onShareAppMessage')
return query
})
onMounted(() => {
console.log('share onMounted')
})
onLoad(() => {
console.log('share uni-app onLoad')
})
return {}
// const init = () => {
// onShareTimeline(() => {
// return query
// })
// onShareAppMessage(() => {
// return query
// })
// }
// return { init }
}
// 页面调用
import useShare from '@/hooks/useShare.js'
useShare () - 发布:2024-04-02 15:20
- 更新:2025-08-25 14:59
- 阅读:755
【报Bug】onShareAppMessage生命周期函数在vue3 hooks写法不生效
产品分类: uniapp/小程序/微信
PC开发环境操作系统: Windows
PC开发环境操作系统版本号: win11
HBuilderX类型: 正式
HBuilderX版本号: 4.07
第三方开发者工具版本号: 1.06
基础库版本号: 3.3.4
项目创建方式: HBuilderX
示例代码:
操作步骤:
写一段hooks技巧的语法,在vue3中,onLoad函数执行,但是onShareAppMessage,onShareTimeline无效
写一段hooks技巧的语法,在vue3中,onLoad函数执行,但是onShareAppMessage,onShareTimeline无效
预期结果:
onShareAppMessage,onShareTimeline内部的方法应该正常执行
onShareAppMessage,onShareTimeline内部的方法应该正常执行
实际结果:
onShareAppMessage,onShareTimeline没有执行
onShareAppMessage,onShareTimeline没有执行
bug描述:
onShareAppMessage 生命周期钩子在hooks写法无效,但是onLoad测试有效
你这么写。核心在于return的函数名字上。
export function useMpShare() {
function share(
options: {
title?: string
path?: NavPageName
imageUrl?: string
} = {}
) {
onShareAppMessage(() => options)
}
function shareFried(
options: {
title?: string
path?: NavPageName
imageUrl?: string
} = {}
) {
onShareTimeline(() => options)
}
return { onShareAppMessage: share, onShareTimeline: shareFried }
}
在其他地方使用
const { onShareAppMessage, onShareTimeline } = useMpShare()
onShareAppMessage({})
const option = {}
onShareTimeline(option)
api.get(...).then(()=>option.title = 'new title')
函数必须在根上(setup或与setup平级)调用,如果是有自定义option,option可以延迟赋值
1***@qq.com
厉害,大佬
2026-04-28 11:34