首页 > 热点 > 微信 > 正文

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

2024-07-22 01:19:21
字体:
来源:转载
供稿:网友

前言

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

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

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

组件通信

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            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表