Search code examples
vue.jsvuejs2vue-componentvuex

Using v-model to bind user input to state in the Vuex store


I have this store:

//store.js

import modulePaciente from './paciente/modulePaciente'
export default new Vuex.Store({
    getters,
    mutations,
    state,
    actions,
    modules: {
        paciente: modulePaciente
    },
})

And ... have this module where I'm trying to use vuex-map-fields

//modulePaciente.js

import { getField,updateField } from "vuex-map-fields";

const state ={
    PacienteData: {
        name: '',
        code: '',
        lastname: '',
    }
}

const mutations ={
    updateField
}

const getters ={
    getField
}

const actions ={...}

export default {
    namespaced: true,
    state,
    mutations,
    getters,
    actions
}

Finally, I have this component:

<template>
  <div id="app">
    <input v-model="name">
    <input v-model="code">
    <input v-model="lastname">
        </div>
</template>
<script>
import { mapFields } from "vuex-map-fields";

export default {
  name: "DatosGeneralesPaciente",
  data: () => ({}),
  computed: {
    ...mapFields("paciente", ["name", "code", "lastname"]),
  },
};
</script>

My problem is that nothing happen when I write in the input model field, when I move to the next input model field the value in the previous input is cleared:

enter image description here

I need to map my store to the v-model component. What am I doing wrong?


Solution

  • Because you've nested your state fields inside PacienteData you must follow the documentation on nested properties.

    The mapFields value should be:

    ...mapFields("paciente", [
      "PacienteData.name",
      "PacienteData.code",
      "PacienteData.lastname",
    ]),
    

    Here is a working codesandbox example