T
T
testopikachu2019-04-03 14:48:19
Vue.js
testopikachu, 2019-04-03 14:48:19

How to make a form using vuex?

Hello, can you please explain how to properly make a form using vuex?
I have a component like this:

<template><div>
  <input type="text" v-model="template.title" />
  <input type="text" v-model="template.name" />
</div></template>
<script>
  export default {
    computed: {
      template() {
        return this.$store.state.templates[this.$route.params.id]
      },
    },

    mounted() {
      if(this.$route.params.id) {
        return this.$store.dispatch('fetchTemplate', this.$route.params.id)
      }
    }
  }
</script>

And such storage
mutations: {
  setTemplate(state, { id, template }) {
    Vue.set(state, id, template)
  },
},

actions: {
  async fetchTemplate({commit}, id) {
    return await axios.get('http://127.0.0.1:8000/api/templates/' + id).then(result => {
      const template = result.data
      commit('setTemplate', { id, template })
    })
  },
}

Isn't that the correct usage?
Form fields become reactive and other components start hooking title and name as you type, and I want the store state to change only after the form is submitted.
I also don’t understand what to do if I don’t want to edit an existing record, but create a new one? In this case, fetchTemplate is not executing, there is nothing else in the computed, and I get the error Cannot read property 'title' of undefined
Thanks!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Yarkov, 2019-04-03
@testopikachu

I want the state of the repository to change only after submitting the form

Then make a local model and after submit call a mutation with this model.
See point one)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question