vue.jsvuex

Is there any benefit of using mapState over mapGetters in Vuex?


I am reviewing company code and see that in one of the Vue components, there are some computed properties that look like this:

  computed: {
    ...mapState('settings', {
      site: state => state.general.site
    }),
    ...mapGetters('settings', [
      'getRouteName'
    ])
  }

Is there a benefit to using mapState over mapGetters? Why wouldn't we just create a mapGetter method for the site just like we did for the routeName?

My thought is maybe the arrow function helps with something but I didn't see anything in the documentation I looked at here: Vuex


Solution

  • Getters allow you to create computed properties (derived state) on the store.

    The getters are methods where you can define a logic to compute the derived state

    An example:

    const store = createStore({
      state: {
        orders: [
          { id: 1, active: true, subtotal: 100 },
          { id: 2, active: false, subtotal: 200 }
        ]
      },
      getters: {
        activeOrders (state) {
          return state.orders.filter(order => order.active)
        },
        total (state) {
           ...
        }
      }
    })
    

    Here is a getter that returns the active orders, and a method that returns the total value of all the orders. Both use the internal state (orders) and generate a derived state.

    It works similar as the Computed properties in Vue Components.