squareborg
squareborg

Reputation: 1621

vuex clean way to bind vuex objects to edit inputs

Does any one have a clean way of binding vuex data to inputs, Say you want to hydrate an edit form with data from vuex, if you don't clone it to a local object before v-modeling it to the input you get mutations errors on input.

This gets particular messy with deep objects with arrays inside as a simple {...object} spread does not clone the nested arrays / objects and the nested arrays will still be tied to vuex.

This is what Im finding my self doing a lot

created() {
    const productId = this.$route.params.id
    this.product = _.find(this.$store.state.vendor.products.list, { id: productId })
    this.getProduct(productId).then(response => {
      this.product = { ...response }
      const clonedVariants = []
      this.product.variants.data.forEach(variant => {
        clonedVariants.push({...variant})
      })
      this.product.variants = {}
      this.product.variants.data = clonedVariants;
      this.freshProduct = true
    })
  },

Upvotes: 1

Views: 220

Answers (1)

codeWisperer
codeWisperer

Reputation: 86

Consider using vuex getters that return a deep cloned version of the state data you need, otherwise as mentioned in the comments consider using lodash deep clone _.cloneDeep or JSON.parse(JSON.strigify(store.state.object))

using a vuex getter to return cloned state:

const store = new Vuex.Store({
  state: {
    products: [
      { id: 1, text: '...' },
      { id: 2, text: '...' }
    ]
  },
  getters: {
    products: state => {
      return _.cloneDeep(state.products)
    }
  }
})

then in the components:

import {mapGetters} from 'vuex';

  export default {
    computed: {
      ...mapGetters(['products'])
    },
    created() {
      const productId = this.$route.params.id
      this.product = _.find(this.products, { id: productId })
    },
}

Upvotes: 1

Related Questions