0

I'm currently doing the below:

<script>
export default {
  computed: {
    editingItem: {
      get() {
        return this.$store.getters['editing/editingItem'];
      },
      set(newValue) {
        this.$store.commit('editing/UPDATE_EDITING', newValue);
      }
    },
    editingItemName: {
      get() {
        return this.editingItem.name;
      },
      set(newValue) {
        this.editingItem.name = newValue;
        this.editingItem = this.editingItem;
      }
    }
  },
}
</script>

Am I over complicating it? The second line on the editingItemName set(), is a workaround to make the editingItem set() function trigger.

2
  • can you explain what you are trying to acheive? are you trying to achieve 2-way data binding with store? Commented Oct 18, 2017 at 7:20
  • @LiranC Yeah. I can do it with a simple state value, but if it has nested parameters, I have to either do like I've done or have a commit for every parameter on the Store. The reason I did like the example is that this way I only have to have one Mutation. Commented Oct 18, 2017 at 11:27

1 Answer 1

2

Check this article. it's about forms, but it shows the way to achieve to 2-way binding with vuex.

regarding your special case, see the code. telephone is a nested property inside an object.

myModule.js

const myModule = {
  state: {
    customerInfo: {
      name: '',
      telephone: ''
    }
  },
  getters: {
    getTelephone(state) {
      return state.customerInfo.telephone
    }
  },
  mutations: {
    setTelephone(state, payload) {
      state.customerInfo.telephone += payload
    },
  }
}
export default myModule;

form.vue

<template>
  <div>
    <input v-model="telephone"></input>
  </div>
</template>

<script>
export default {
  computed: {
    telephone: {
      get() {
        return this.$store.getters['getTelephone']
      },
      set(value) {
        this.$store.commit('setTelephone', value)
      }
    },
  }
}
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

Cool. It looks like what I was doing - besides that I'm reusing the same mutation for every nested parameter. Do you think I should have one mutation to every parameter or what I'm doing is ok? Will mark your answer as correct as I do think that is the way to do it right now!

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.