bigWhite
bigWhite
  • 发布:2024-06-29 13:38
  • 更新:2024-07-19 15:36
  • 阅读:325

uniapp 重写Page 方法不生效

分类:uni-app

需求是 重新小程序的Page生命周期

uniapp 如何重写 小程序的 Page 方法  
在原生小程序好用 但是uniapp 编译的不行  
这是什么原因?有解决办法吗
代码:

"use strict";  

(function() {  
  let originalPage = Page;  
  console.log('init-0',Page)  

  try{  
    Page = (pageParams) => {  
          console.log('init-1')  
      const { onLoad, onShow, onReady } = pageParams;  
      pageParams.onLoad=(params)=>{  
        setTimeout(()=>{  
          console.log('开始')  
         setTimeout(()=>{  
          onLoad && onLoad.call(this, params);  
         },2000)  
        },3000)  
      }  

      return originalPage(pageParams);  
    };  
  }catch(e){  
    //TODO handle the exception  
    console.log(e)  
  }  

})();
2024-06-29 13:38 负责人:DCloud_UNI_yuhe 分享
已邀请:
DCloud_UNI_yuhe

DCloud_UNI_yuhe

uniapp编译后中的createPage中使用的时Component而不是Page,所以代码不会生效

  • bigWhite (作者)

    那怎么解决 能不能提供个思路

    2024-07-01 15:59

  • bigWhite (作者)

    或者怎么达到类似的效果 应该怎么实现

    2024-07-01 16:01

  • DCloud_UNI_yuhe

    回复 bigWhite:暂时还找不到实现的方法,如果想要实现类似的效果,可以这样,虽然有点难看,但能实现


    <template>  
    <view class="margin">
    <scroll-view class="scroll" scroll-y="true">
    <textarea class="text-area"></textarea>
    <view v-for="i in 1000">{{i}}</view>
    </scroll-view>
    </view>
    </template>

    <script>
    export default {
    data() {
    return {

    }
    },
    onLoad(data) {
    console.log("data",data)
    },
    methods: {

    }
    }
    // #ifdef MP-WEIXIN
    const onload = _sfc_main.onLoad
    _sfc_main.onLoad=(params)=>{
    setTimeout(()=>{
    console.log('开始')
    setTimeout(()=>{
    onload && onload.call(this, params);
    },2000)
    },3000)
    }
    // #endif

    </script>

    <style>
    .scroll{
    height: 800rpx;
    }
    .margin{
    margin-left: 20rpx;
    }
    .text-area{
    width: 700rpx;
    height: 200rpx;
    background-color: lightpink;
    }
    </style>

    2024-07-01 16:08

  • bigWhite (作者)

    回复 DCloud_UNI_yuhe: 那怎么注册一个全局的 就是不管那个页面的onload 都给他挟持

    另外你这个方法确实好用

    2024-07-01 16:19

  • DCloud_UNI_yuhe

    回复 bigWhite: 确实麻烦,我去看下

    2024-07-01 16:26

  • bigWhite (作者)

    回复 DCloud_UNI_yuhe: okok 等你回复

    2024-07-01 16:32

  • bigWhite (作者)

    回复 DCloud_UNI_yuhe: 你给的方案 是重写页面的onload 但是当页面原本就有onload方法的时候他俩是 共存的 ,而我想实现的是 在所有页面加载的时候先执行一个方法 (可能是异步方法)等这个方法执行完毕 再去加载页面本身的 onLoad 钩子,感觉有点像三方的统计 不知道他们是怎么实现的?

    2024-07-01 16:46

DCloud_UNI_yuhe

DCloud_UNI_yuhe

解决方法:在App.vue中添加如下代码

<script>  
    export default {  
        onLaunch: function() {  
            console.log('App Launch')  
        },  
        onShow: function() {  
            console.log('App Show')  
        },  
        onHide: function() {  
            console.log('App Hide')  
        }  
    }  
    // #ifdef MP-WEIXIN  
    const componentExtend = (Component) => {  
        return (object) => {  
            const {  
                methods  
            } = object;  
            const {  
                onLoad  
            } = methods;  
            object.methods.onLoad = function(options) {  
                console.log("开始执行");  
                if (typeof onLoad === "function") {  
                    console.log(`${this.route}的onLoad执行 ----------`);  
                    onLoad.call(this, options);  
                    console.log(`${this.route}的onLoad执行完毕 ----------`);  
                }  
            };  
            return Component(object);  
        };  
    };  
    const originalComponent = Component;  
    Component = componentExtend(originalComponent);  
    // #endif  
</script>  

<style>  
    /*每个页面公共css */  
</style>

暂时能符合你的需求,但是要注意检查代码是否会造成其它影响

  • bigWhite (作者)

    非常棒老哥 给你点赞

    2024-07-16 08:58

  • l***@163.com

    app 怎么改呢

    2024-08-28 17:02

  • l***@163.com

    app 也可以用这一套?

    2024-08-28 17:02

d***@junrunrenli.com

d***@junrunrenli.com

我这个方式是否可行?目前用着没啥问题

import { mapGetters, mapState } from 'vuex'  
import { appUtil, pageUtil } from '@/utils'  
import { LOGIN_CHECK_WHITE_LIST } from '@/constant/pages'  
import dictMixin from '@/mixins/dictMixin'  

export default {  
  mixins: [dictMixin],  
  data() {  
    return {  
      /**  
       * @type {Record<string, any>}  
       */  
      pageParams: {},  
      prevPage: {},  
      route: '',  
      mixinPageLoading: true  
    }  
  },  
  computed: {  
    ...mapState('user', {  
      __getUserInfoPromise: 'getUserInfoPromise'  
    }),  
    ...mapGetters('user', {  
      __userInfo: 'userInfo',  
      __token: 'token'  
    }),  
    mixinPageType() {  
      let mpType = this.mpType  
      // #ifdef APP-PLUS  
      if (mpType === undefined) {  
        mpType = 'component'  
      }  
      // #endif  

      // #ifdef MP  
      if (mpType === undefined) {  
        mpType = 'app'  
      }  
      // #endif  

      return mpType  
    }  
  },  
  beforeCreate() {  
    const oldOnLoad = this.$options.onLoad || []  
    const oldCreated = this.$options.created || []  
    const oldOnShow = this.$options.onShow || []  
    this.$options.onLoad = oldOnLoad.map((item, index) => {  
      return async function (e) {  
        this.__setPageData(e)  
        if (index === 0) {  
          await this.__getDict()  
        } else {  
          await this.$nextTick()  
          await this.__getDict()  
        }  

        this.__onLoadPromiseResolve = null  
        this.__onLoadPromise = new Promise((resolve) => {  
          this.__onLoadPromiseResolve = resolve  
        })  
        item.call(this, e)  
        await this.$nextTick()  
        this.__onLoadPromiseResolve()  
      }  
    })  
    this.$options.onShow = oldOnShow.map((item) => {  
      return async function (e) {  
        if (this.mixinPageType === 'page') {  
          try {  
            const _pages = pageUtil.getPages()  
            const route = _pages[_pages.length - 1].route  
            const isWhiteListPage = LOGIN_CHECK_WHITE_LIST.includes(`/${route}`)  
            if (!isWhiteListPage) {  
              await this.__getUserInfoPromise  
            }  
          } catch (err) {  
            console.log(err)  
          }  
          await this.mixinDictHasReady  
          await appUtil.nextTick()  
          if (this.__onLoadPromise) {  
            await this.__onLoadPromise  
          }  
        }  
        await item.call(this, e)  
      }  
    })  
    this.$options.created = oldCreated.map((item, index) => {  
      return async function (e) {  
        if (this.mixinPageType === 'page') {  
          try {  
            const _pages = pageUtil.getPages()  
            const route = _pages[_pages.length - 1].route  
            const isWhiteListPage = LOGIN_CHECK_WHITE_LIST.includes(`/${route}`)  
            if (!isWhiteListPage) {  
              await this.__getUserInfoPromise  
            }  
          } catch (err) {  
            console.log(err)  
          }  
        }  
        if (this.mixinPageType === 'component') {  
          if (this.$options.dictKey?.length) {  
            if (index === 0) {  
              try {  
                await this.__getDict()  
              } catch (err) {  
                console.log(err)  
              }  
            } else {  
              await this.mixinDictHasReady  
            }  
          }  
        }  

        item.call(this, e)  
      }  
    })  
  },  
  async onLoad() {},  
  methods: {  
    __setPageData(e) {  
      this.pageParams = e || {}  
      const _pages = pageUtil.getPages()  
      this.prevPage = _pages.length > 1 ? _pages[_pages.length - 2] : _pages[_pages.length - 1]  
      this.route = _pages[_pages.length - 1].route  
    },  
    mixinClosePageLoading() {  
      this.mixinPageLoading = false  
    }  
    // __getAllDictKeys(vm, dictKeys = []) {  
    //   let { dictKey = [] } = vm.$options || {}  
    //   dictKeys.push(...dictKey)  
    //   const children = vm.$children  
    //   if (children.length) {  
    //     children.forEach((item) => {  
    //       vm.__getAllDictKeys(item, dictKeys)  
    //     })  
    //   }  
    //   return dictKeys  
    // }  
  }  
}
  • d***@junrunrenli.com

    重新了每一个onLoad,onshow, created, 坑不少,通过promise强制控制了先执行onload再执行onshow,保障onshow能拿到onload中得到的props

    2024-07-19 15:41

要回复问题请先登录注册