1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

vuexでフォームを扱う(getとset)

Last updated at Posted at 2021-02-08

概要

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を呼び出す

参考文献

vuex公式
v-modelでstateやgettersを変更したい時に使える算出プロパティ

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?