Search code examples
vue.jsdata-bindingnuxt.jsstatevuex

2 way Binding Nuxt.js


I'm trying to find a pattern that I can use that will allow me to update the State on input. I've tried several patterns including the get set method that is in the official docs, but I can't seem to get anything to work. I can get changes in the state to show on my page with an {{email}} but not the other way around when filling out a form. I'd appreciate any solutions at this point.

<template>
  <section>
    <BaseInput placeholder="Email" type="text" :value="email" @input="updateEmail" />
  </section>
</template>

<script>
import { mapState } from 'vuex'

export default {
  components: {
    BaseInput,
  },
  computed: {
    ...mapState({
      email: (state) => state.email,
    }),
  },
  methods: {
    updateEmail(email) {
      this.$store.commit('updateEmail', email)
    },
  },
}
</script>

index.js

export const state = () => ({
  email: '',
})

export const mutations = {
  updateEmail(state, payload) {
    state.email = payload
  },
}

Solution

  • If you look for the eventListener, you'll get the whole Event object: https://developer.mozilla.org/en-US/docs/Web/API/Event

    If you want to use only the value of the field, you need to use

    this.$store.commit('updateEmail', email.target.value)
    

    PS, some points to take into consideration:

    • try to put more effort into formatting when posting your question
    • do not use mutations but rather actions (core thing in Vuex)
    • either use only the helpers (mapState, mapActions etc...) or direct Vuex ($store.state, $store.commit etc...) try to not mix both