1. 程式人生 > 實用技巧 >uni app使用mobx | uni app狀態管理mobx

uni app使用mobx | uni app狀態管理mobx

使用mobx的響應函式autorun監聽狀態變化進行賦值和執行函式,頁面onLoad時執行所有autorun,頁面onUnload時銷燬所有autorun

observer.ts

import {autorun, IReactionDisposer, IReactionPublic, reaction, toJS} from 'mobx'

// 響應 Mobx ,對 Observables 作出響應
export const Observer = <T extends { new(...args: any[]): any }>(constructor: T) => {
  return
class ObserverClass extends constructor { disposer: IReactionDisposer[] = [] reaction: string[] = [] autorun: string[] = [] onLoad(evt: any) { super.onLoad && super.onLoad(evt) if (super.autorun) { this.disposer = this.disposer || [] this.disposer.push(...super.autorun.map((x) => autorun((this
as any)[x].bind(this)))) } if (super.reaction) { this.disposer.push(...super.reaction.map((x) => { return (this as any)[x]() })) } } onUnload() { super.onUnload && super.onUnload() if (this.disposer) { this.disposer.forEach(x => x())
this.disposer.length = 0 } } } } // autorun操作 export const Render = (target: any, key: string, descriptor: TypedPropertyDescriptor<() => void>) => { target.autorun = target.autorun || [] target.autorun.push(key) } // autorun操作 export const Autorun = (target: any, key: string, descriptor: TypedPropertyDescriptor<() => any>) => { target.autorun = target.autorun || [] target.autorun.push(key) } // Reactor操作 export const Reactor = (target: any, key: string, descriptor: TypedPropertyDescriptor<() => IReactionDisposer>) => { target.reaction = target.reaction || [] target.reaction.push(key) } // 和Reactor搭配進行副作用操作 export const React = <T>(expression: (r: IReactionPublic) => T, effect: (arg: T, r: IReactionPublic) => void) => { return reaction(expression, effect, {fireImmediately: true}) } // 狀態轉屬性 export function State(value: any) { return function (target: any, key: string): any { let funcKey = 'store_to_' + key target[funcKey] = function () { this[key] = toJS(this.store[value]) } target.autorun = target.autorun || [] target.autorun.push(funcKey) } }

index.vue

<template>
  <div class="index">
    <h1>store.step: {{store.step}}</h1>
    <h1>step: {{step}}</h1>
    <h1>step2: {{step2}}</h1>
  </div>
</template>

<script lang="ts">
import {Vue, Component, Prop, Watch} from "vue-property-decorator";
import {Autorun, Observer, State} from '@/utils/observer';
import {store} from '@/utils/store'

@Component
@Observer //必須緊貼index元件
export default class index extends Vue {

  //名稱必須為store
  store = store

  //單向 state.tep -> this.step ,修改 this.step 不影響 state.step
  @State('step')
  step: string = ''

  step2: string = ''

  //mobx 的監聽函式 autorun
  @Autorun
  autorun_step() {
    this.step2 = store.step
  }

  onLoad(evt?: any) {
    console.log('onLoad.evt', evt)

    store.step = 'aaa'
    setTimeout(() => {
      store.step = 'bbb'
    }, 1000)
  }

}
</script>

<style scoped lang="stylus">

.index
  padding 0

</style>

本文地址:

https://www.cnblogs.com/stumpx/p/13408962.html