概要
Vueを使ってフォームのinput要素を双方向データバインディングを作成する場合、dataに変数を宣言してv-modelから取得していましたが、vuexを導入してstateに変数を宣言していた場合の方法を起筆します。
実装方法
改善前(Vuexを導入していない)
comment.vue
<template>
<div class="comments">
<form v-on:submit.prevent="submit">
<textarea name="comment" id="comment" cols="30" rows="10" v-model="comment"></textarea>
<button>コメントを送信する</button>
</form>
</div>
</template>
<script>
export default {
data(){
comment:''
},
methods: {
submit() {
this.$store.dispatch('comment/pushComment');
},
},
}
</script>
改善後(Vuexを導入した手法)
comment.vue
<template>
<div class="comments">
</div>
<form v-on:submit.prevent="submit">
<textarea name="comment" id="comment" cols="30" rows="10" v-model="comment"></textarea>
<button>コメントを送信する</button>
</form>
</div>
</template>
<script>
export default {
computed: {
comment:{
get(){
return this.$store.getters['comment/comment'];
},
set(value){
this.$store.commit('comment/updateComment', value);
}
},
},
methods: {
submit() {
this.$store.dispatch('comment/pushComment');
},
},
}
</script>
comment.js
import axios from "axios";
const state = {
comment: null,
};
const getters = {
comment: state => state.comment ? state.comment: '',
};
const mutations = {
updateComment(state,comment){
state.comment = comment;
}
};
const actions = {
pushComment({context}, data){
axios.post('/api/comment').then(result=>{
}).catch(error=>{
})
}
};
export default {
namespaced: true,
state,
getters,
mutations,
actions
}
まとめ
.js
computed: {
comment:{
get(){
return this.$store.getters['comment/comment'];
},
set(value){
this.$store.commit('comment/updateComment', value);
}
},
},
・値を返すときはget()を利用して、gettersを返す
・値を変更するときはset()を利用して、mutationsを呼び出す