Vuexのstateをv-modelで使う際に、フォームの入力について下記の公式リファレンスを参考にしました。
https://vuex.vuejs.org/ja/guide/forms.html
ここで質問ですが、mapMutationsを使ってcommitの部分を書き換えることは可能でしょうか?
下記に現在作成途中のアカウント新規登録画面のコード添付します。
Signup.vue
1<template> 2<div class="signup"> 3 <h2>新規登録</h2> 4 <input type="text" placeholder="Username" v-model="updateUsername"> 5 <input type="text" placeholder="email" v-model="updateEmail"> 6 <input type="password" placeholder="Password" v-model="updatePassword"> 7 <button @click="signUp({email, password})">登録する</button> 8</div> 9</template> 10 11<script> 12import { 13 username, 14 email, 15 password 16} from '../store/index.js' 17import { 18 mapGetters 19} from 'vuex' 20import { 21 mapMutations 22} from 'vuex' 23 24export default { 25 name: 'Signup', 26 data() { 27 return { 28 username, 29 email, 30 password 31 } 32 }, 33 methods: { 34 ...mapMutations([ 35 'signUp' 36 ]) 37 }, 38 computed: { 39 ...mapGetters([ 40 'getUsername', 41 'getEmail', 42 'getPassword' 43 ]), 44 updateUsername: { 45 get() { 46 return this.getUsername 47 }, 48 set(value) { 49 this.$store.commit('updateUsername', value) //ここをmapMutationsを用いてthis.updateUsername(value)としたい。以下の2つの算出プロパティについても同じ。 50 } 51 }, 52 updateEmail: { 53 get() { 54 return this.getEmail 55 }, 56 set(value) { 57 this.$store.commit('updateEmail', value) 58 } 59 }, 60 updatePassword: { 61 get() { 62 return this.getPassword 63 }, 64 set(value) { 65 this.$store.commit('updatePassword', value) 66 } 67 } 68 } 69} 70</script> 71 72<style scoped> 73input { 74 display: flex; 75 flex-direction: column; 76 justify-content: center; 77 font: 16px/24px sans-serif; 78 width: 230px; 79 padding: 10px 0; 80 margin: 10px auto; 81 border: none; 82 border-bottom: 1.5px solid #1b2538; 83} 84 85input:focus { 86 border-bottom: 1.5px solid #da3c41; 87 outline: none; 88 transition: .5s; 89} 90 91button { 92 color: #FFF; 93 background-color: #1da1f3; 94 border-radius: 20px; 95 display: inline-block; 96 margin: 10px auto; 97 height: 40px; 98 width: 120px; 99 font-size: 16px; 100 border: none; 101} 102 103button:active { 104 background-color: #36c; 105} 106 107button:focus { 108 outline: 0px; 109} 110</style>
index.js
1import Vue from 'vue' 2import Vuex from 'vuex' 3import firebase from 'firebase' 4 5Vue.use(Vuex) 6 7export default new Vuex.Store({ 8 state: { 9 username: '', 10 email: '', 11 password: '' 12 }, 13 getters: { 14 getUsername: state => state.username, 15 getEmail: state => state.email, 16 getPassword: state => state.password 17 }, 18 mutations: { 19 signUp({ email, password }) { 20 firebase 21 .auth() 22 .createUserWithEmailAndPassword(email, password) 23 .then(user => { 24 alert('Create account: ' + user.user.email) 25 }) 26 .catch(error => { 27 alert(error.message) 28 }) 29 }, 30 updateUsername(state, value) { 31 state.username = value 32 }, 33 updateEmail(state, value) { 34 state.email = value 35 }, 36 updatePassword(state, value) { 37 state.password = value 38 } 39 }, 40 actions: {}, 41 modules: {} 42})