Created
August 19, 2019 12:57
-
-
Save rochabianca/17d0443fc243470ca8abcec08c1a02e9 to your computer and use it in GitHub Desktop.
Function to map fields direct on vuex
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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