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

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>
👤LiranC

Leave a comment