1

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
    })
  },
1
  • 1
    Use a deep cloning function. JSON.parse + JSON stringify if you have only have JSON datatypes, otherwise _.cloneDeep Commented Jun 20, 2020 at 22:13

1 Answer 1

1

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 })
    },
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.