LoginSignup
4
2

More than 3 years have passed since last update.

beforeRouteEnterからvuex storeのactionを実行したいとき

Last updated at Posted at 2019-10-18

ルーティング前に何がしかの判定をして、リダイレクトしたりとかしたいときありますよね。
somValuetrue のときだけ、遷移を許可したいとか。
別に非同期である必要はないのですが、今回はたまたま。

import store from '@/store';
import { mapGetters, mapActions } from 'vuex';

export default {
  beforeRouteEnter (to, from, next) {
    store.dispatch('yourAction')
      .then(() => {
        if (store.getters['yourGetter'].someValue) {
          next();
        } else {
          next({ path: '/' });
        }
      });
  },

  created () {
    this.yourAnotherAction();
  },

  computed: {
    ...mapGetters('yourModule', [
      'yourAnotherGetter'
    ])
  },

  methods: {
    ...mapActions('yourModule', [
      'yourAnotherAction'
    ])
  }
}

やりたいことは実現できたし、Vue.jsの作者がそう言ってるので、良いのかな、と思うのだけど・・・。

なんか・・・変な気がする・・・。これでいいのか・・・?

※ツッコミお待ちしてます。

参考

Vue Router / ナビゲーションガード

4
2
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
4
2