Victor Mikó
Victor Mikó

Reputation: 379

2 way-binding with a nested property inside object. (VueJS + VueX)

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.

Upvotes: 0

Views: 1049

Answers (1)

LiranC
LiranC

Reputation: 2480

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>

Upvotes: 2

Related Questions