LoginSignup
1

More than 5 years have passed since last update.

VuexのmapXxxで動的な名前空間を使う

Posted at

VueコンポーネントでmapActionsとか使うときに、名前空間をpropsdataから取得したかった。
で、以下のように書いてもthisは存在しないのでエラー。


<script>
export default {
  props: ['path'],

  // エラー
  computed: mapState(this.path, ['someState']),

  // エラー
  methods: mapActions(this.path, ['someAction'])
}
</script>

そんなときはオブジェクトを渡してやればOK。

<script>
export default {
  props: ['path'],

  computed: mapState({
    someState (state) {
      return state[this.path]['someState'];
    }
  }),

  methods: mapActions({
    someAction (dispatch) {
      dispatch(this.path + '/someAction');
    }
  })
}
</script>

参考

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