国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 熱點 > 微信 > 正文

微信小程序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            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 建宁县| 醴陵市| 盐源县| 白山市| 崇州市| 柳河县| 西宁市| 阜南县| 新沂市| 凤山市| 兴宁市| 都匀市| 牟定县| 乌海市| 平塘县| 河池市| 灌阳县| 雷山县| 屯昌县| 中超| 河间市| 定襄县| 和政县| 浦县| 曲水县| 藁城市| 新野县| 嵊泗县| 搜索| 尉氏县| 百色市| 天等县| 施甸县| 神农架林区| 民和| 阿图什市| 龙里县| 沧源| 上蔡县| 洛川县| 昌平区|