Help us understand the problem. What is going on with this article?

Vuex:mapState,mapGetters,mapActions,mapMutationsの使い方

「これ何に使うの?」と思ったら予想外に便利なので書く。

store.js

例えばこんなstoreがあるとします。

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state:{
    hoge:'',
  },
  getters:{
    hogetters: (state) => state.hoge,    
  },
  mutations:{
    updateHoge(state,payload){
      const self = this
      self.state.hoge = payload
    },
  },
  actions:{
    getHoge(value){
      const self = this
      self.dispatch('updateHoge',value)
    }
  },
});

Sample.vue

Componentsの最初に読み込んでおきます。

<script>
import { mapState, mapGetters, mapActions, mapMutations } from "vuex";
export default {
  name: 'HogeVue',
  computed:{
    ...mapState({
      hoge:'hoge',
    })
    ...mapGetters({
      hogetters:'hogetters',
    }),
  },
  methods:{
    ...mapActions({
      getHoge:'getHoge',
    }),
    ...mapMutations({
      updateHoge:'updateHoge',
    }),
  },
}
</script>

すると、こんな風にラクに書けます。

<template lang="pug">
  .sample
    h1 {{hogetters}}
    p(@click="getHoge('fuga')") {{hoge}}
</template>
<script>
  //(上記map...は省略します)
  methods:{
    sample(){
      const self = this
      self.updateHoge('fuga')
    },
  },
</script>

storeの値を呼び出す時に
this.$store.state.hoge
this.$store.getters.hogetters
と毎回書いていくと、数が多くなるにつれてダルくなってきますので、
使うものは最初にmap...に書いてあげたほうがあとあとラクになります。

mapGettersmapActionsは特に沢山呼び出す時は使えると思います。
以上です。

DaisukeNishi
エンジニアに憧れるデザイナーです。性格診断は「INTP」思いやり・社交性に欠ける人。。→ http://xn--16-573d25rtpd1v4e.com/intp.php
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした