s***@163.com
s***@163.com
  • 发布:2020-07-31 13:06
  • 更新:2020-07-31 13:06
  • 阅读:989

uni app使用mobx | uni app状态管理mobx

分类:uni-app

使用mobx的响应函数autorun监听状态变化进行赋值和运行函数,页面onLoad时执行所有autorun,页面onUnload时销毁所有autorun

以下是ts代码模板

<template>  
  <div class="${NAME}">  

  </div>  
</template>  

<script lang="ts">  
import {Vue, Component, Prop, Watch} from "vue-property-decorator";  
import {autorun, observe, toJS} from "mobx";  
import _ from 'lodash';  
import {store} from '@/utils/store'  

@Component  
export default class ${NAME} extends Vue {  

  /*创建监听*/  
  createDisposer() {  
    //观察状态变化  
    this.disposer.push(autorun(() => {  
      //this.step3 = store.step  
    }))  
  }  

  //映射监听  
  createDisposerMap(obj: any) {  
    const _this = this  
    _.forOwn(obj, (v, k) => {  
      _this.disposer.push(autorun(() => {  
        if (_.isArray(obj)) {  
          _this[v] = toJS(store[v])  
        } else {  
          _this[k] = toJS(store[v])  
        }  
      }))  
    })  
  }  

  //销毁监听  
  destroyDisposer() {  
    this.disposer.map(x => x())  
    this.disposer.length = 0  
  }  

  //监听列表  
  disposer: Function[] = []  

  onUnload() {  
    this.destroyDisposer()  
  }  

  onLoad(evt?: any) {  
    this.createDisposer()  
    //this.createDisposerMap(['step'])  
    //this.createDisposerMap({step2: 'step'})  
  }  

}  
</script>  

<style scoped lang="stylus">  

.${NAME}  
  padding 0  

</style>  
0 关注 分享

要回复文章请先登录注册