How to save form data to a global obj using Vuex Vue.js with Laravel 5.8

Asked

Viewed 382 times

0

Good guys, in my first component I have this obj ready.

    export default {
        data: () => ({
            valid: false,
            campo: {
                endereco: '',
                numero: '',
                bairro: '',
                cep: '',
                cidade: '',
                estado: '',
                complemento: '',
            }
 }),

I’d like to take the field obj in other Formulars using vuex. my app.js store is like this

    const store = new Vuex.Store({
    state:{
        global:{}
    },
    Mutations:{
        setItem(state,obj){
            state.global = obj;
        }
    }
});

My biggest difficulty is to pass this obj to the store and then discover the correct syntax to use in another component.

1 answer

0

To achieve your goal you can use two Vuex helpers, the mapState and the mapMutations.

Let’s take an example, the code below will create your store with a global form and Mutation to set the form:

import Vue from "vue";
import App from "./App.vue";
import Vuex from "vuex";

Vue.config.productionTip = false;

Vue.use(Vuex);

new Vue({
  render: h => h(App),

  store: new Vuex.Store({
    globalForm: {
      username: ""
    },
    mutations: {
      setForm(state, form) {
        state.globalForm = form;
      }
    }
  })
}).$mount("#app");

Then, within your component, you can do the following to use the mutation (this.form is your form):

import { mapMutations } from "vuex";

export default {
  methods: {
    ...mapMutations(["setForm"]),

    setFormData() {
      this.setForm(this.form);
    }
  }
};

And ai to retrieve the form content you can do so on any component (with this.globalForm):

import { mapState } from "vuex";

export default {
  computed: {
    ...mapState(["globalForm"])
  },
};

Maybe your code isn’t working because Mutations should be lowercase when you create the store.

  • This syntax is to use in project 100% Vue.js right? ?

  • @Rafael, I left the example of how it could be done, so just you adapt to your needs. I don’t know how it works in Laravel.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.