mobxjs / mobx-vue

🐉 Vue bindings for MobX
MIT License
475 stars 22 forks source link

Some doubt #23

Closed Penggggg closed 5 years ago

Penggggg commented 6 years ago

How can i detect mobx variable changing in vue ? Thx

Penggggg commented 6 years ago

inject.ts ( inject some store into vue instance )

import { Observer } from 'mobx-vue';
import { mappingStore } from '../store';

type injectArg = {
    selector?: (keyof typeof mappingStore)[ ]
};

export const inject = ( injectOpt: injectArg ) => {
    return view => {
        if ( Array.isArray( injectOpt.selector )) {
            injectOpt.selector.map( storeName => {
                view.prototype[ storeName ] = mappingStore[ storeName ];
            });
        }
        return Observer( view );
    };
};

.vue ---> function no trigger

<script lang="ts">
import { inject } from '../inject';
import { Component, Vue, Watch } from 'vue-property-decorator';

@inject({
    selector: ['account$']
})
@Component({ })
export default class AccountBind extends Vue {

   @Watch('account$.wx.isBind')
    onBind( val ) {
        // no matter how 'isBind' change, this function cannot be trigger
        console.log('?');
    }

}
</script>

.vue - But i can see changing in template

<template>
   <div>
      {{ account$.wx.hasBeenBound }}
  </div>
</template>
kuitos commented 6 years ago

use mobx observe instead of vue watch https://mobx.js.org/refguide/observe.html#observe

Penggggg commented 5 years ago

@kuitos I'm sorry, but i can't understand how can i detect mobx variable changing in vue

.vue

import { observe } from 'mobx';

somfunction( ) {
   observe( a$.wx.systemUser, ( change => {
            console.log( change ); // not working
    }));
}

mounted( ) {
    this.somfunction( )
}
Penggggg commented 5 years ago

@kuitos

.vue template

   <!-- can show change -->
   <div>{{ $account.wx.user }}</div>
   <!-- cannot show change -->
   <div>{{ user }}</div>

.vue ts

   get user( ) {
       console.log( '??' ) // cannot detect the change
       return this.$account.wx.user;
   }
kuitos commented 5 years ago

Could you please make a minimal reproduction with codesandbox?

kuitos commented 5 years ago

observe( a$.wx.systemUser, ( change => { console.log( change ); // not working }));

fix to

observe(a$.wx, 'systemUser', change => console.log(change))

check the observe api https://mobx.js.org/refguide/observe.html#observe

kuitos commented 5 years ago

closed as not active any more