LoginSignup
1
1

More than 1 year has passed since last update.

...mapState でストア呼び出し

Last updated at Posted at 2021-04-25

mapstateとは

一言でいうと、ストアのデータ呼び出しの記述を短くするためのもの、です。
this.$store.state.プロパティ名 でストアのデータを呼び出スことが可能です。しかしそれでは長くなり、可読性が落ちてしまうので computed にまとめて呼び出すことができます。

mapStore自体がオブジェクトを返すのでこのようにします。

<script>

import { mapState } from "vuex"; // vuexからmapStateをimport

export default {
  computed: mapState(["lists"]),
};
</script>

本来はコンポーネント内で this.$store.state.lists と記述しますが、 mapState を使うことで、 state に this.$store.state が代入され、簡潔に呼び出しができます

computed と mapstate を共存させるには

最初に紹介した方法では、computedが定義できませんが、こんな記述方法もあります。

computed: {

  ...mapState(["lists"]),

  otherFunction() {
    // 略
  },
},

... ←の意味

これ( ... ) はスプレッド構文という名前で、オブジェクトを個々の値に展開することができるものです。

スプレッド構文を使わず下記の様にしてしまうと・・

computed: {
  mapState(['lists']),
}

mapstateがオブジェクトを返すので、このように {} が重なった状態になってしまいます。

computed: {

  {
    lists () {
      return this.$store.state.lists
    },
  }

}

参考文献

Vue公式 Vuex state

1
1
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
1