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

3,069 阅读2分钟

前言

数据通信在开发中是必不可少的一个环节,也是我们必须掌握的知识。知道得越多的数据通信方式,实现业务会更加得心应手。

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

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

组件通信

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: []
    })
  }
})

写在最后

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