小程序注册全局组件

  开发框架是的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)
}

  这样就可以全局调用弹窗组件了。有可能有更好的方法~

小程序注册全局组件

上一篇:微信小程序富文本解析器的使用


下一篇:小程序异步获取openid解决方案