Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

vue.js - Storing Form Values in Vuex Via Object

I have a search form and an object like this:

<!-- Search.vue -->
<template>
  <form>
    <input type="text" v-model="form.firstName">
    <input type="text" v-model="form.lastName">
  </form>
</template>

<script>
export default {
  data() {
    return {
      form: {
        firstName: '',
        lastName: '',
      }
  }
}
</script>

I'm wanting to move the form data object to my Vuex store so I can save the form settings if the user navigates away from this component.

Ideally, I would like to do something like this, but even though this works, I get errors:

<template>
  <form>
    <input type="text" v-model="form.firstName">
    <input type="text" v-model="form.lastName">
  </form>
</template>

<script>
export default {
  computed: {
    form() {
      get() {
        return this.$store.state.form;
      },
      set(values) {
        this.$store.commit('SET_FORM', values)
      }
    },
  }
}
</script>
// store.js
export default {
  state: {
    form: {
      firstName: '',
      lastName: '',
    }
  },
  mutations: {
    SET_FORM(state, values) {
      state.form = values;
    },
  },
}
Error: [vuex] do not mutate vuex store state outside mutation handlers.

Here's my alternative approach, but I feel like this is way too complicated.

<template>
  <form>
    <input type="text" v-model="firstName">
    <input type="text" v-model="lastName">
  </form>
</template>

<script>
export default {
  computed: {
    firstName() {
      get() {
        return this.$store.state.form.firstName;
      },
      set(value) {
        this.$store.commit('SET_FORM', { attribute: 'firstName', value: value })
      }
    },

    lastName() {
      get() {
        return this.$store.state.form.lastName;
      },
      set(value) {
        this.$store.commit('SET_FORM', { attribute: 'lastName', value: value })
      }
    },
  }
}
</script>
// store.js
export default {
  state: {
    form: {
      firstName: '',
      lastName: '',
    }
  },
  mutations: {
    SET_FORM(state, { attribute, value }) {
      state.form[attribute] = value;
    },
  },
}

Anyone know why I would be getting the Vuex errors and how I could fix them? Either that or know of a better way to approach this?

Thanks!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...