> 文章列表 > 微信小程序想给每个页面都加上分享功能,可以全局的加吗?

微信小程序想给每个页面都加上分享功能,可以全局的加吗?

微信小程序想给每个页面都加上分享功能,可以全局的加吗?

每个页面都设置onShareAppMessage方法,让每个页面都可以分享

然后发现了一个wx.onAppRoute

wx.onAppRoute(() =>{console.log('当前页面路由发生变化 触发该事件onShareAppMessage')const pages = Taro.getCurrentPages() //获取加载的页面const view = pages[pages.length - 1] //获取当前页面的对象if(!view) return false //如果不存在页面对象 则返回// 若想给个别页面做特殊处理 可以给特殊页面加isOverShare为true 就不会重写了// const data = view.data// if (!data.isOverShare) {// data.isOverShare = trueconsole.log(123123, view);Taro.showShareMenu({showShareItems: ['shareAppMessage', 'shareTimeline']})view.onShareAppMessage = () => { //重写分享配置return {title: 'AI 秀(show)出你的美',path: "/pages/index/index", //若无path 默认跳转分享页imageUrl: 'https://mobvoi-ai-public.cn-bj.ufileos.com/FOLDER/image/generation/2023-03-29/1641026841173315586.png',}}view.onShareTimeline = () => { //重写分享配置return {title: 'AI 秀(show)出你的美',path: "/pages/index/index", //若无path 默认跳转分享页imageUrl: 'https://mobvoi-ai-public.cn-bj.ufileos.com/FOLDER/image/generation/2023-03-29/1641026841173315586.png',}}// }
})
也可以全局监听页面路由。如果没有登陆并且需要注册就去注册页面

wx.onAppRoute((route) => {

    const protectedRoutes = [

      'pages/protected/1',

      'pages/protected/2',

      'pages/protected/3'

    ]

    if (!store.userLoggedIn() && protectedRoutes.find(r => route.path.includes(r))) {

      wx.redirectTo({

        url: '/pages/register/register'

      })

    }

 })