Vuex: Auto-map objects inter-state

Created on 23 Apr 2016  路  2Comments  路  Source: vuejs/vuex

While thinking of my other ideas, I think this would be an elegant solution to most of the issues outlined in #145.

If we can do this:

// products.js
export default {
    state: {
        all: [
            { id: 1, name: "Toy" },
            { id: 2, name: "Battery" },
            { id: 3, name: "Laptop" }
        ]
    }
}
// cart.js
export default {
    state: {
        items: [
            { productId: 1, quantity: 1 },
            { productId: 3, quantity: 2 }
        ],
        starId: null,
        status: 'ok'
    },
    map: { // Mapping reference ids to actual object in other state
        starId: { map: "products.all.id", to: "starProduct" },
        items: {
            productId: { map: "products.all.id", to: "product" }
        }
    },
}
// component.js
export default {
    //...
    vuex: {
        getters: {
            cartItems: state => state.cart.items
        }
    }
    methods: {
        console.log(this.cartItems[0]) // => { productId: 1, product: { id: 1, name: "Toy" }, quantity: 1 }
        console.log(this.cartItems[0].product) // => {id: 1, name: "Toy" }
    }
}

Would save a lot of work with having to find the other object in the Vue component.

Most helpful comment

I like the auto mapping, but I don't think that should be done directly inside the module. It could be kinda like an optional schema layer that auto-creates getters for you. This way it is more composable.

All 2 comments

I like the auto mapping, but I don't think that should be done directly inside the module. It could be kinda like an optional schema layer that auto-creates getters for you. This way it is more composable.

In 2.0 this can be achieved via getters.

const store = new Vuex.Store({
  getters: {
    cartItems: state => {
      // whatever mapping logic you want...
    }
  }
})

You can also define custom helpers to simplify the creation of such getters.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jdittrich picture jdittrich  路  3Comments

fnlctrl picture fnlctrl  路  4Comments

james-wasson picture james-wasson  路  3Comments

Sarke picture Sarke  路  3Comments

visualjerk picture visualjerk  路  3Comments