Skip to content

Instantly share code, notes, and snippets.

@rochabianca
Created August 19, 2019 12:57
Show Gist options
  • Save rochabianca/17d0443fc243470ca8abcec08c1a02e9 to your computer and use it in GitHub Desktop.
Save rochabianca/17d0443fc243470ca8abcec08c1a02e9 to your computer and use it in GitHub Desktop.
Function to map fields direct on vuex
<template>
<form>
<label for="email">Email</label>
<input type="email" id="email" name="email" v-model="email" />
<label for="senha">Senha</label>
<input type="password" id="senha" name="senha" v-model="senha" />
</form>
</template>
<script>
import { mapFields } from '@/helpers.js';
export default {
computed: {
...mapFields({
fields: ['email', 'senha'],
base: "usuario",
mutation: 'UPDATE_USUARIO',
}),
}
}
</script>
/*
Author: @origamid
This code is not mine. I get it from the course 'Vue.js Completo' from Origamid
(https://www.origamid.com/curso/vue-js-completo/) and find it very useful, so I'm saving here to future use.
*/
export function mapFields(options) {
const object = {};
for (let x = 0; x < options.fields.length; x++) {
const field = [options.fields[x]];
object[field] = {
get() {
return this.$store.state[options.base][field];
},
set(value) {
this.$store.commit(options.mutation, { [field]: value });
}
};
}
return object;
}
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
strict: true,
state: {
usuario: {
email: '',
senha: '',
}
},
mutations: {
UPDATE_USUARIO(state, payload) {
state.usuario = Object.assign(state.usuario, payload);
}
},
actions: {
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment