微信小程序公共頁(yè)面封裝

小程序在公共全局的基礎(chǔ)方法和變量這一塊并不支持。已知的全局變量存取也不是很方便。

本文章能解決的問(wèn)題:

  • 實(shí)現(xiàn)在所有page中 js,wxml頁(yè)面里使用公共的data和方法;
  • 實(shí)現(xiàn)公共Page處理公共屬性和邏輯(比如全局登錄彈框);

1.使用minxi的概念將公共Page合并到每一個(gè)Page里面:

  • 新建 minxi.js 存放在until文件夾下。
const nativePage = Page
const lifecycle = ['onLoad', 'onReady', 'onShow', 'onHide', 'onUnload', 'onPullDownRefresh', 'onReachBottom', 'onShareAppMessage', 'onPageScroll']
let globalMixin = null

//全局mixin方法
wx.mixin = function(config){
  if(isType(config,'object')){
    globalMixin = config
  }
}
//原生Page代理
Page = function (config) {
  let mixins = config.mixins
  //加入全局mixin
  if(globalMixin){                                                         
    (mixins || (mixins=[])).unshift(globalMixin)
  }
  if (isType(mixins, 'array') && mixins.length > 0) {
    Reflect.deleteProperty(config, 'mixins')
    merge(mixins, config)
  }
  nativePage(config)
}

function merge(mixins, config) {
    mixins.forEach(mixin => {
      if (isType(mixin, 'object')) {
        //合并data、生命周期以及其他數(shù)據(jù)
        Object.keys(mixin).forEach(key => {
          if (key === 'data') {
            config[key] = Object.assign({}, mixin[key], config[key])
          } else if (lifecycle.includes(key)) {
            let nativeLifecycle = config[key]
            config[key] = function () {
              let arg = Array.prototype.slice.call(arguments)
              mixin[key].call(this, arg)
              return nativeLifecycle && nativeLifecycle.call(this, arg)
            }
          } else {
            config[key] = mixin[key]
          }
        })
      }
    })
  }
  
  //判斷類(lèi)型工具
  function isType(target, type) {
    let targetType = Object.prototype.toString.call(target).slice(8, -1).toLowerCase()
    type = type.toLowerCase()
    return targetType === type
  }
  • 新建 common-page.js ,用于處理公共邏輯
// 此為公共參數(shù) 方法區(qū)
//添加全局公共參數(shù)、方法 :這里面的方法參數(shù)將合并到每一個(gè)Page里面 優(yōu)先級(jí)比所屬Page低

export const mixinStr = {
    data: {
      comm_showLoginDialog: false, //控制登錄彈框
      comm_imageUrl: "https://***.com/images", //小程序圖片資源目錄
      comm_pageInfo:{ //前端首次加載頁(yè)面信息
        "pageNum": 1,
        "pageSize": 10,
        "total": 1,
        "totalPage": 1,
      }
    },
    onReady:function () {
      var mApp = getApp()
    this.setData({
      comm_globalData: mApp.globalData,
    })
    },
    comm_goLogin() {//喚起登錄
      this.setData({
        comm_showLoginDialog: true
      })
    },
    comm_resetPageInfo(){ //重置頁(yè)面屬性
      this.setData({
        comm_pageInfo:{
          "pageNum": 1,
          "pageSize": 10,
          "total": 1,
          "totalPage": 1,
        } 
      })
    },
    comm_addPageNum(){ //頁(yè)面加一
      var mPageinfo = this.data.comm_pageInfo
      mPageinfo.pageNum = mPageinfo.pageNum + 1
      this.setData({
        comm_pageInfo: mPageinfo
      })
    },
    //跳轉(zhuǎn)webview
    comm_goWebPage(url){
      wx.navigateTo({
        url: '../../pages/webview/webview?url='+url,
      })
    },
    //顯示普通toast
    comm_showToast(str){
      if (str != null && str != undefined && str != '') {
        wx.showToast({
          title: str,
          icon: "none"
        })
      }
    },
    //顯示成功toast
    comm_showSuccessToast(str){
      if (str != null && str != undefined && str != '') {
        wx.showToast({
          title: str,
          icon:"success"
        })
      }
    },
    //顯示失敗toast
    comm_showFailToast(str){
      if (str != null && str != undefined && str != '') {
        wx.showToast({
          title: str,
          icon:"error"
        })
      }
    },
    //返回
    comm_onBackBtnClick(){
      wx.navigateBack({
        delta: 0,
      })
    }

  }
  • 然后在app.js 里面調(diào)用 minxis.js中minxi方法,這樣所有的Page將會(huì)合并我們的common-page.js中的內(nèi)容,這樣我們就可以在所有的Page里無(wú)縫使用公共方法和屬性了
//添加全局公共參數(shù)、方法 :這里面的方法參數(shù)將合并到每一個(gè)Page里面
 require('./utils/mixins.js')
wx.mixin(mixinStr)
...
App({
...
})
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。
禁止轉(zhuǎn)載,如需轉(zhuǎn)載請(qǐng)通過(guò)簡(jiǎn)信或評(píng)論聯(lián)系作者。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容