LoginSignup
1
1

More than 3 years have passed since last update.

JavaScript の Vuex で mapGetters や mapActions などの候補を表示させる helper パターン (Type Vuex without TypeScript 参考)

Posted at

JavaScript の Vuex で mapGetters や mapActions などの候補を表示させる helper パターン

この記事は Type Vuex without TypeScript - ITNEXT を参考にしています。
基本的な内容はリンク先にて確認したほうがよいと思われます。
Type Vuex without TypeScript - ITNEXT では chrisvfritz/vue-enterprise-boilerplate を紹介しており
mapGetters などの具体的使用例として挙げています。

Type Vuex without TypeScript - ITNEXT

上記の記事の概要としては大体以下のような感じのようです。

  • TypeScript を使用せず Vuex の mapGetters や mapActions を Vue コンポーネント使用時に定義内容を候補をインテリセンスで表示させたい
  • プラグインをできるだけ使わないとなると chrisvfritz/vue-enterprise-boilerplateChris’ helper pattern のような形にになる
  • JSDoc で注釈をつけてあげれば型の表示なども可能
  • もし Vuex に breaking changes が適用された場合には事例内の helper.js の定義内で吸収が可能かも

keyof との組み合わせ

紹介されている事例では以下のような記述に対し authComputedauthMethods に JSDoc により注釈をつけるというものです。

chrisvfritz/vue-enterprise-boilerplate/src/state/helpers.js
import { mapState, mapGetters, mapActions } from 'vuex'

export const authComputed = {
  ...mapState('auth', {
    currentUser: (state) => state.currentUser,
  }),
  ...mapGetters('auth', ['loggedIn']),
}

export const authMethods = mapActions('auth', ['logIn', 'logOut'])

これだと一つ一つ定義していかなければならないので・・・
State, getters, actionsimport してそれぞれ mapGetters などに渡してしまいます。
State というのは こちらの構成 にしているものです。
Nuxt.js にてやってます。

store/profile/helper.js
import { mapState, mapGetters, mapActions } from 'vuex';
// eslint-disable-next-line
import { State } from './state';
import getters from './getters';
import actions from './actions';

// eslint-disable-next-line
const stateAlias = {
  currentUser: 'namae',
};

/**
 * @type {{[K in keyof stateAlias]: State[stateAlias[K]]} & {[K in keyof getters]: getters[K]}}
 */
export const profileComputed = {
  ...mapState('profile', {
    currentUser: state => state.namae,
  }),
  ...mapGetters('profile', Object.keys(getters)),
};

/**
 * @type {{[K in keyof actions]: actions[K]}}
 */
export const profileMethods = mapActions('profile', Object.keys(actions));

これを実際に使ってみると・・・

<template>
  <div>
    infer js blank {{ $store.getters['profile/getNamae'] }} {{ currentUser }}
  </div>
</template>

<script>
import { profileComputed, profileMethods } from '@/store/profile/helper';

export default {
  computed: {
    ...profileComputed,
  },
  mounted() {
    this;
  },
  methods: {
    ...profileMethods,
  },
};
</script>

this

なんか・・・型があやしいですが・・・一応推論されています。

inferred-action

インテリセンスで候補として表示され、 Action の中身も一応見れています。

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