微信小程序8种数据通信的方式总结

下面我将这些通信方式归类介绍:

  • 组件通信
  • 全局通信
  • 页面通信

一、组件通信

properties

 父组件向子组件通信,与 Vue 的 props 作用相同。

父组件向子组件传数据:

<my-component list="{{list}}"></my-component>

子组件接收数据:

Component({  
   properties:{    
       list:{      
         type: Array,      
         value: []    
       }  
   },  
   attached(){    
     console.log(this.list)  
   }
})

triggerEvent

子组件向父组件通信,与 Vue 的 $emit 作用相同

子组件触发自定义事件:

Component({  
    attached(){    
      this.triggerEvent('customEvent',{ id: 10 })  
    }
})

父组件接收自定事件:

<my-component list="{{list}}" bind:customEvent="customEvent"></my-component>
Page({  
    customEvent(e){    
        console.log(e.detail.id)  
    }
})

selectComponent

使用选择器选择组件实例节点,返回匹配到的第一个组件实例对象,类似 Vue 的 ref

<my-component id="mycomponent" list="{{list}}"></my-component>
Page({  
    onLoad(){    
        let mycomponent = this.selectComponent('#mycomponent')     mycomponent.setData({ 
          list: []    
        })  
    }
})

selectOwnerComponent

选取当前组件节点所在的组件实例(即组件的引用者),返回它的组件实例对象,类似 Vue 的 $parent

Component({  
    attached(){    
     let parent = this.selectOwnerComponent() 
      console.log(parent)  
     }
})

二、全局通信

globalData

将数据挂载到 app.js,这种方式在开发中很常用。通过getApp(),我们能够在任何一个页面内访问到app实例。

app.js 

App({  
    globalData:{    
        list:[]  
    }
})

page1.js

const app = getApp()Page({
    onLoad(){
        app.globalData.list.push({
          id: 10    
        })  
    }
})

page2.js

const app = getApp()Page({  
    onLoad(){    
         console.log(app.globalData.list) // [{id:10}]  
    }
})

storage

storage并不是作为通信的主要方式。storage 主要是为了缓存数据,并且最多只能存储10M的数据,我们应该合理使用storage

wx.setStorageSync('timestamp', Date.now());
wx.getStorageSync('timestamp');
wx.removeStorageSync('timestamp');

eventBus

通过发布订阅模式注册事件和触发事件进行通信

简单实现

class EventBus{
  constructor(){
    this.task = {}
  }
  on(name, cb){
    if(!this.task[name]){
      this.task[name] = []
    }
    typeof cb === 'function' && this.task[name].push(cb)
  }
  emit(name, ...arg){
    let taskQueen = this.task[name]
    if(taskQueen && taskQueen.length > 0){
      taskQueen.forEach(cb=>{
        cb(...arg)
      })
    }
  }
  off(name, cb){
    let taskQueen = this.task[name]
    if(taskQueen && taskQueen.length > 0){
      let index = taskQueen.indexOf(cb)
      index != -1 && taskQueen.splice(index, 1)
    }
  }
  once(name, cb){
    function callback(...arg){
      this.off(name, cb)
      cb(...arg)
    }
    typeof cb === 'function' && this.on(name, callback)
  }
}
export default EventBus

使用

app.js

import EventBus from '/util/EventBus'
wx.$bus = new EventBus()

page1.js

Page({  
    onLoad(){    
        wx.$bus.on('add', this.addHandler)  
    },  
    addHandler(a, b){    
        console.log(a+b)  
    }
})

page2.js

Page({  
  onLoad(){    
    wx.$bus.emit('add', 10, 20)  
  },
})

三、页面通信

getCurrentPages

getCurrentPages() 获取当前页面栈,数组中第一个元素为首页,最后一个元素为当前页面

元素为一个对象,里面存放着页面的信息,包括route(页面路径)、options(onLoad拿到的参数)、method、data等

Page({
  onLoad(){
    let pages = getCurrentPages()
    let lastPage = pages[pages.length-2]
    lastPage.setData({
      list: []
    })
  }
})

如果你还有其他的通信方式,欢迎交流~

评论

暂无评论