使用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 个评论
要回复文章请先登录或注册