Search code examples
vue.jsvuex

Vuex -- mapState in parent and pass as prop, or mapState directly in child?


If I'm loading a large object in App.vue and committing it to the store at init, is it better to do the mapStating in a parent component and pass the object to the a child (where it will be iterated / used / displayed) or is it better to mapState the object directly in the child where it is being used?

Followup... does either make a difference in availability of someBigArray? I find I always have to deep watch mapStated objects and assign them to local data() variables on change which feels like such a hack.

// state.someBigArray

// ---------------------------------------> parent 

<template>
  <Child :the-object="someBigArray"/>
</template>
computed: mapState(["someBigArray"]),

// ---------------------------------------> child 

<template>
  <div v-for="item in someBigArray">
     {{ item.name }}
  </div>
</template>

<script>
export default {
props: {
  locations: {
    type: Array,
    required: true,
    default: () => [],
  },
}


Solution

  • You can get data from Vuex where you want to, depending on your specific case. But if your child component is a UI component that is not supposed to do any calculations, I'd better passed all data with props, no matter how big it is.

    Also you can avoid such hack by making a getter for your data and using mapGetters in computed section of your component. And I find using mapState a bit not secure, so I prefer using mapGetters instead.

    Update

    Actually Vuex docs encourages use of mapState, so it seems that getters are unnecessary if you don't need to modify data in some way.