2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Nuxt] 記事投稿後にthis.$router.pushできなかった件について

Posted at

きっかけ

railsとNuxtを使用してWebメディアもどきを作成しています。
admin画面で記事を投稿(=axiosでpost)したあとにtopへリダイレクトさせようと
this.$router.push("/")を記載しましたがうまく機能しませんでした。

問題

以下のようなコードを書いていました。

  methods: {
    async onSubmitted(data) {
      await this.$axios
        .$post('/api/v1/articles', data)
        .then( data => {
          this.$router.push("/")
        })
        .catch(e => {
          console.log(e)
        })
    }
  }

axiosでpostしたあと、成功すればtopへ飛ばすという実装です。
これが飛んでくれません。

解決策1

data使ってないのにthenの引数にdataを渡すのもおかしいよな、と思い
普通のアロー関数() =>に直したところ、動きました。

  methods: {
    async onSubmitted(data) {
      await this.$axios
        .$post('/api/v1/articles', data)
        .then( () => {
          this.$router.push("/")
        })
        .catch(e => {
          console.log(e)
        })
    }
  }

解決策2

念の為、dataを使用することもあるだろうと思い
(引数)としたところこちらもうまくいきました。

  methods: {
    async onSubmitted(data) {
      await this.$axios
        .$post('/api/v1/articles', data)
        .then( (data) => {
          this.$router.push("/")
        })
        .catch(e => {
          console.log(e)
        })
    }
  }

けど

アロー関数の引数ってたしか()省略できるんじゃなかったっけ…
=> 思い込みかと感じ調べたところ、やっぱり省略できるらしいです。
https://jsprimer.net/basic/function-declaration/

うーん、、

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?