mobxjs / mobx-vue

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

How to make props reactive? #16

Closed snaptopixel closed 6 years ago

snaptopixel commented 6 years ago

Is there a way to make this reactive?

<my-component :my-prop="someMobxModelObject"></my-component>
kuitos commented 6 years ago

uh... Exactly I didn't understood what u mean... Could u please explain it in detail or make a codesandbox demo?

snaptopixel commented 6 years ago

Sorry @kuitos, my initial post was vague. Let me phrase it in a different way...

When using mobx-vue, what is the pattern for passing component props? Here's what I've been doing which is not ideal...

class ViewModel {
   @observable account: AccountModel // This is a mobx store
   constructor() {
    autorun(() => {
      // Do stuff when this.account changes
    });
  }
}

@Observer
@Component
export default class AccountDetails {
  state = new ViewModel();
  // I'd like to map this into the state automatically somehow
  @Prop() account: AccountModel = null; 
  // In but instead I need to do this?
  @Watch('account') setAccount() { this.state.account = this.account; }
}
kuitos commented 6 years ago

If your the prop account only changed once after component mounted, u can pass the account to your ViewModel over a dependency injection way.

@Observer
@Component
export default class AccountDetails {
  get state() {
    return new ViewModel(this.account);
  }
}

Or u might be interested in the specified solution provided by mmlpx di

While your account changed around the component lifecycle, and you wanna reassign state account dynamically, @Watch maybe the only way imo.

But what made me curious was that why you wanna watch the account prop in AccountDetails, rather than the parent component who pass the account down?