MorJS aPage/wPage Mixins 支持

2024-01-15 17:38 更新

小程序在 Component 的維度上支持的 mixins,使用 mixins 能夠解耦業(yè)務(wù)可復(fù)用邏輯,因此 MorJS 在 Page 的維度上也實(shí)現(xiàn)了  mixins 的機(jī)制,使用上基本與 Component 一致,提供 { mixins: [mixin1, mixin2] } 的 mixin 數(shù)組即可。有以下的注意點(diǎn):

  • mixin 必須是一個(gè)對象,里面是希望給 aPage / wPage 合并的各種屬性
  • dataObject 類型的對象屬性均會(huì)合并
  • 生命周期的鉤子函數(shù)會(huì)合并依次執(zhí)行,aPage / wPage 選項(xiàng)的生命周期最后執(zhí)行
  • Object 類型的屬性(如:函數(shù))會(huì)被同名的屬性覆蓋,aPage / wPage 選項(xiàng)的屬性優(yōu)先級最高
import { aPage } from '@morjs/core'

const mixinA = {
  data: {
    x: 1,
    y: 2
  },
  onLoad() {
    console.log('mixina', 'onLoad')
  },
  foo() {
    console.log('mixina', 'foo')
  },
  test: {
    t: 1,
    o: 3
  },
  no: 'xxxx'
}

const mixinB = {
  data: {
    z: 3
  },
  onLoad() {
    console.log('mixinb', 'onLoad')
  },
  mixinBMethod() {
    console.log('mixinb', 'mixinBMethod')
  },
  foo() {
    console.log('mixinb', 'foo')
  },
  test: {
    t: 2
  },
  no: 'hahaha'
}

aPage({
  mixins: [mixinA, mixinB],
  onLoad() {
    // 生命周期依次打印 mixina onLoad -> mixinb onLoad -> page onLoad
    console.log('page', 'onLoad')
    // 執(zhí)行的是 mixinB 的 foo 方法
    this.foo()
    // { x: 1, y: 2, z: 3 } mixinA 和 mixinB 的 data 會(huì)合并
    console.log(this.data)
    // { o: 3, t: 2 } mixinA 和 minxinB 都設(shè)置了 test 的 t
    // mixinB 的 test.t 會(huì)覆蓋 mixinA 的 test.t
    console.log(this.test)
    // hahaha minxinB 會(huì)覆蓋 minxinA 的同名屬性
    console.log(this.no)
    // 當(dāng)前實(shí)例會(huì)有 mixin 提供的方法
    console.log(this.mixinBMethod)
  }
})


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號