Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What is going on with this article?
@DaisukeNishi

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

More than 1 year has passed since last update.

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

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は特に沢山呼び出す時は使えると思います。
以上です。

0
Help us understand the problem. What is going on with this article?
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
DaisukeNishi
エンジニアに憧れるデザイナーです。性格診断は「INTP」思いやり・社交性に欠ける人。。→ http://xn--16-573d25rtpd1v4e.com/intp.php

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
0
Help us understand the problem. What is going on with this article?