LoginSignup
0
0

More than 5 years have passed since last update.

mapActionsの第2引数のオブジェクトのメンバーに関数を指定すると何が嬉しいのか?

Posted at

その関数とは以下のように書いてある

Object's item can be a function which accept dispatch function as the first param, it can accept anthor params. You can dispatch action and do any other things in this function. specially, You need to pass anthor params from the mapped function.

コードで表すと

import { mapActions } from 'vuex';

export default {
  // 省略
  methods: {
    ...mapActions({
      // Object's item can be a function which accept `dispatch` function as the first param, it can accept anthor params
      submit(dispatch, name, email) {
                // do any other things in this function
        if (!this.termsOfServiceChecked) {
          alert('利用規約に同意してください');
          return;
        }

        // specially, You need to pass anthor params from the mapped function
        dispatch('registerUser', { name, email });
      }
    }
  }
}

以下のような書き方もできるが、マッピングが増えてくるとregisterUserはマッピングしたものかが分かりづらくなりコードが読みにくくなる印象がある。


import { mapActions } from 'vuex';

export default {
  // 省略
  methods: {
    ...mapActions(['registerUser']),
    submit(name, email) {
      if (!this.termsOfServiceChecked) {
        alert('利用規約に同意してください');
        return;
      }

      this.registerUser({ name, email});
    }
  }
}

以下のようにマッピングしたメソッド呼ぶ前に、バリデーションなど事前にしておきたい処理がなければ、
mapActionsの第2引数のオブジェクトのメンバーは関数がいいかもしれないと思いました。


<template>
<button @click="fetch">
</template>

<script>
import { mapActions } from 'vuex';

export default {
  methods: {
    ...mapActions(['fetch'])
  }
}
</script>

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