vuejs / Discussion

Vue.js discussion
167 stars 17 forks source link

vuex store and route data hook #368

Closed azamat-sharapov closed 9 years ago

azamat-sharapov commented 9 years ago

Need your recommendations on using vue-router on top of vuex architecture.

// in items store
const state = {
  items: []
}

// --------------

// in vm
data () {
  items: itemsStore.state.items
},
route: {
  data () {
    // inside promise function:
    return {
      items: fetchedData
    }
  }
}

Code above shows, that I'm setting vm.items in router's data hook, after fetching from server. I need to save that data into itemsStore, but here, it's only saved in vm.items.

I have some thoughts about setting fetched data into store:

  1. Fetch items in store action and call that action in data hook. But problem I see here, is that vuex actions do not return data, that is probably by design.
  2. After fetching items in router data hook, save them in store first and then return that data. But that seems verbose.

I'm playing with flux architecture first time, so I may be missing something. What are your recommendations on this?

azamat-sharapov commented 9 years ago

Learning more about Flux, I found out, that I actually need to change state in the store itself, via action. So I created seedItems() action. And in route data hook, I'm simply calling $actions.seedItems(fetchedItems). Also found out, that vue-router calls transtion.next() automatically, if I just return promise, so no need to return object or anything else.

But any other recommendation are welcome :)

yyx990803 commented 9 years ago

Yep, if you are using vuex, any change to state should be handled via an action, and the actual "set" should happen in the store's action handler.

Another problem here is that you want the vm to hold the reference to the root state object, not just the item. Because if the store replaces state.items, the vm won't get the update.

Vuex is still pretty much an experiment though. I'll revisit the pattern once 1.0.0 work is done...

azamat-sharapov commented 9 years ago

Thanks Evan! It's going smooth so far, I like it :)