小程序注冊全局組件


  開發框架是的uniapp.

  組件庫中沒有找到可以現用的全局可調用的彈窗,只能使用微信提供的wx.showToast()。這個方法可以實現在項目每個位置都可以調用的邏輯。只是最多只可以修改彈窗中的圖片。不能滿足自定義全局彈窗的功能。

  在參考https://zhuanlan.zhihu.com/p/183919769 后,在代碼基礎上做了修改。

  首先,我們需要在創建好自己的公共組件。customer-toast.提供一個_show方法可以展示彈窗。

  接下來在main.js中import 組件,綁定組件在全局上。

  創建vue.config.js。

module.exports = {
  chainWebpack: (config) => {
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap((options) => {
        const compile = options.compiler.compile
        options.compiler.compile = (template, ...args) => {
          if (args[0].resourcePath.match(/^pages/)) {
            template = template.replace(
              /[\s\S]+?<[\d\D]+?>/,
              (_) => `${_}
                <custom-toast  ref="custom-toast" />
              `
            )
          }
          return compile(template, ...args)
        }
        return options
      })
  }
}

  我們在頁面上使用this.$refs.custom-taost._show(msg,type)。可以展示彈窗。

  展示彈窗方法可以綁定在vue對象上,我們可以在每一個頁面使用this.customToast(title,type)來使用。

Vue.component('custom-toast', CustomToast)
Vue.prototype.customToast = function (title, type) {
  this.$refs['custom-toast']['_show'](title, type)
}

  在公共js方法中調用組件,this指向目的不統一。我通過獲取小程序當前頁面的屬性,方法來獲取到refs來展示彈窗。

const _toast = function (msg, type) {
  const pages = getCurrentPages()
  const ctx = pages[pages.length - 1]
  ctx.$vm.$refs['custom-toast']['_show'](msg, type)
}

  這樣就可以全局調用彈窗組件了。有可能有更好的方法~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM