MPVue传值

最近上手mpvue开发微信小程序,发现mpvue官网没有提供页面反向传值的解决方案,于是广查资料,知道eventbus解决方案,再结合之前的iOS通知,写了一个文件来实现pages间的反向传值。
1、新建一个notification.js文件

// 用来存放监听事件
let _notifications = []

/* 添加监听事件
* notificationName  事件传递名称
* selector          事件回调函数
* observe           事件监听者
* */
function addNotification (notificationName, selector, observe) {
  console.log('addNotification=', notificationName, 'selector=', selector, 'observe=', observe)
  if (!notificationName || !selector || !observe) {
    console.log('addNotification error')
    return
  }

  let alreadyNotifi = false
  try {
    _notifications.forEach(item => {
      if (item.name === notificationName && item.selector === selector && item.observe === observe) {
        alreadyNotifi = true
        throw new Error('该实例或组件已添加该通知')
      }
    })
  } catch (e) {
    if (e.message !== '该实例或组件已添加该通知') {
      throw e
    }
  }

  if (alreadyNotifi) {
    console.log('该实例或组件已添加该通知')
    return
  }

  let notification = {
    name: notificationName,
    selector: selector,
    observe: observe
  }

  _notifications.push(notification)
}

/* 发送通知
* notificationName 事件名称
* payload          事件回调函数所需参数
* */
function postNotification (notificationName, payload) {
  console.log('postNotification=' + notificationName, 'payload=', payload)
  if (!notificationName) {
    console.log('postNotification error')
    return
  }

  _notifications.forEach(item => {
    if (item.name === notificationName) {
      item.selector(payload)
    }
  })
}

/* 移除监听
* notificationName 事件名称
* observe          监听者
* */
function removeNotification (notificationName, observe) {
  console.log('removeNotification=' + notificationName, 'observe=', observe)
  if (!notificationName || !observe) {
    console.log('removeNotification error')
    return
  }

  _notifications.forEach((item, index) => {
    if (item.name === notificationName && item.observe === observe) {
      _notifications.splice(index, 1)
    }
  })
}

export default {
  addNotification,
  postNotification,
  removeNotification
}

2、在需要添加监听的地方

// 2.1
  import notificationCenter from '../../utils/notification'
//2.2
  notificationCenter.addNotification('fromdetail', this.fromdetail, this)

3、在发起通知的地方

//3.1
  import notificationCenter from '../../utils/notification'
//3.2
 onLoad () {
   notificationCenter.addNotification('fromindex', this.fromindex, this)
 },
 onUnload () {
   notificationCenter.removeNotification('fromindex', this)
 },
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,148评论 1 32
  • 国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿:20170802 前言: 排版 ...
    庭说阅读 11,211评论 6 13
  • 1)使用《牛津英语搭配词典》查“hitch”,了解它作为名词时的常用搭配。 slight, last-minute...
    罗罗ph阅读 168评论 0 0
  • 天空阴沉 偶有阵阵微风吹过 里面夹杂着冰凉的水汽 可让树木摇曳绿叶 让花朵释放芳香 亦让人在感受丝丝凉意并抖擞精神...
    张小另阅读 229评论 0 3
  • 让我想想,记性比2011年生大嘻之前差很多,俗话说一孕傻三年,我一直想不明白。在更多与他人的交流中,我确信不是生育...
    大溪源阅读 269评论 0 0