51
38

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 5 years have passed since last update.

Vuex で modules を利用した際の getters の使い方

Last updated at Posted at 2018-05-16

vuex 1ファイルの行数が増えすぎたのでリファクタついでにmodules 使い始めたら少しひっかかったので書き溜め。

構成

components/record.vue
<template>
  <div>
    {{record.length}}
  </div>
</template>
<script>
  import { mapGetters } from 'vuex'
  export default {
    computed: {
      ...mapGetters(['record']) // NG
    },
    record_count() {
      return this.$store.getters.record.length; // NG
    }
  }
</script>
vuex/modules/Record/index.js
export default {
  state: {},
  getters: {record: []},
  mutations: {},
  actions: {},
}
vuex/index.js
import Record from './modules/Record'

export default new Vuex.Store({
  modules: {
    Record,
  }
})

this.$store.getters の呼び出し

    record_count() {
      return this.$store.getters.record.length; // NG
    }

解決策

getters にはただのオブジェクトなので、当たり前だけど一応。

    record_count() {
      return this.$store.getters['Record/record'].length; // OK
    }

<template> 使いたい場合の mapGetters 指定

    computed: {
      ...mapGetters(['record']) // NG
    },

解決1

    computed: {
      ...mapGetters({ record: 'Record/record'}) // OK
    }

解決2

    computed: {
      ...mapGetters('Record', ['record']), // OK
    }

こっちの書き方が出来るとは思わなかった。

参考

Vueたのしいよ

51
38
2

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
51
38

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?