【開源】騰訊 omi-mp-create 發佈 - 極小卻精巧的小程序框架

【開源】騰訊 omi-mp-create 發佈

極小卻精巧的小程序框架,對小程序入侵性幾乎爲零 → Githubgit

omi-mp-create 和 omio 同樣,使用了 omi packages 裏的 obaa 監聽數據變化自動更新視圖。和早期發佈的 westore 對比的話,就是不用 diff 了,數據變動以後 setData 的最短路徑自動就出來了,性能上一個檔次。github

5分鐘精通 omi-mp-create

API

  • create.Page(option) 建立頁面
  • create.Component(option) 建立組件
  • create.mitt() 事件發送和監聽器
  • create.emitter 事件發送和監聽器
  • this.oData 操做頁面或組件的數據(會自動更新視圖)
  • this.store 頁面注入的 store,頁面和頁面全部組件能夠拿到

實戰

頁面

import create from '../../utils/create'

const app = getApp()

create.Page({
  store: {
    abc: '公共數據從頁面注入到頁面的全部組件',
    //事件發送和監聽器,或者 create.mitt()
    emitter: create.emitter
  },
  data: {
    motto: 'Hello World',
    userInfo: { },
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo')
  },
  ...
  ...
  onLoad: function () {

    ...
    ...
    ...
     //監聽事件
    this.store.emitter.on('foo', e => console.log('foo', e) )
    
    setTimeout(() => {
      this.oData.userInfo = {
        nickName: 'dnt',
        avatarUrl: this.data.userInfo.avatarUrl
      }
    }, 2000)


    setTimeout(() => {
      this.oData.userInfo.nickName = 'dntzhang'
    }, 4000)
  }
})
複製代碼

這裏須要注意,oData 必須直接操做 data 裏定義好的數據才能直接更新視圖,好比 nickName 一開始沒有定義好,更新它是不會更新視圖,只有經過下面代碼執行以後,才能更新 nickName,由於 userInfo 的變動會自動監聽 userInfo 內的全部屬性:小程序

this.oData.userInfo = {
  nickName: 'dnt',
  avatarUrl: this.data.userInfo.avatarUrl
}
複製代碼

固然你也能夠直接在 data 裏聲明好:數組

data: {
    motto: 'Hello World',
    userInfo: { nickName: null },
    ...
複製代碼

組件

import create from '../../utils/create'

create.Component({
  data: {
    a: { b: Math.random() }
  },

  ready: function () {
    //這裏能夠或者組件所屬頁面注入的 store
    console.log(this.store)
    //觸發事件
    this.store.emitter.emit('foo', { a: 'b' })
    setTimeout(()=>{
      this.oData.a.b = 1
    },3000)
  },
})
複製代碼

數組

import create from '../../utils/create'
import util from '../../utils/util'

create.Page({
  data: {
    logs: []
  },
  onLoad: function () {
    this.oData.logs = (wx.getStorageSync('logs') || []).map(log => {
      return util.formatTime(new Date(log))
    })

    setTimeout(() => {
      this.oData.logs[0] = 'Changed!'
    }, 1000)

  }
})
複製代碼

這裏須要注意,改變數組的 length 不會觸發視圖更新,須要使用 size 方法:微信

this.oData.yourArray.size(3)
複製代碼

其餘

this.oData.arr.push(111) //會觸發視圖更新
//每一個數組的方法都有對應的 pureXXX 方法
this.oData.arr.purePush(111) //不會觸發視圖更新

this.oData.arr.size(2) //會觸發視圖更新
this.oData.arr.length = 2 //不會觸發視圖更新

複製代碼

mitt 語法

const emitter = mitt()

// listen to an event
emitter.on('foo', e => console.log('foo', e) )

// listen to all events
emitter.on('*', (type, e) => console.log(type, e) )

// fire an event
emitter.emit('foo', { a: 'b' })

// working with handler references:
function onFoo() {}
emitter.on('foo', onFoo)   // listen
emitter.off('foo', onFoo)  // unlisten
複製代碼

詳細參見 mitt githubapp

Todo

  • supports fn props

誰在使用

微信支付

立刻使用

→ Github框架

MTI Lic

相關文章
相關標籤/搜索