js提取指定网站内容(js中自定义初始化方法页面中获取全局数据的时候获取不到)

优采云 发布时间: 2022-01-21 23:15

  js提取指定网站内容(js中自定义初始化方法页面中获取全局数据的时候获取不到)

  在微信小程序app.js中初始化全局数据是个好主意,但是有些数据需要异步获取,导致无法获取页面中的全局数据。目前的解决方案如下。

  app.js 中的自定义初始化方法

  wxLogin() {

    // 登录

    return new Promise((resolve, reject) => {

        //自己的业务,可能是 异步请求服务端的,如果是异步请求的就请求成功后 resolve(res)

        wx.login({success: function(res) {

          ....

          resolve(res)

        })

     

    })

},

_appRoute(obj){

    console.log('_appRoute-curPath', this.globalData.curPath)

    if (!this.globalData.curPath){

      return

    }

    //_appRoute是在appInt中执行

   //拿到 当前路由页面路径和传入的 obj 可以自己做一些判断 this.globalData.curPath,比如在某些条件下跳转到指定页面等等

    ...

},

appInt(){

    return this.wxLogin().then(obj => {

      this._appRoute(obj);

      return obj

    });

},

onLaunch(e) {

    let that = this;

    console.log('onLaunch',e);

    //注意这个 wx.onAppRoute 一旦启动,不受控制,而且它执行的比较早,所以这里如果获取到 当前页面路径(res.path)后直接 赋值到全局 this.globalData.curPath = res.path;

    //后续的方法执行的时候 判断下 this.globalData.curPath 是否存在,不存在返回。

    wx.onAppRoute((res) => {

      wx.hideHomeButton(); //隐藏新版小程序左上角的home图标      

      that.globalData.curPath = res.path;

      console.log('onLaunch-curPath', that.globalData.curPath);

    })

},

globalData: {

    curPath:''

}

  在页面中调用:

0 个评论

要回复文章请先登录注册


官方客服QQ群

微信人工客服

QQ人工客服


线