3
1

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.js で title に fetch で取得した値を設定する

3
Last updated at Posted at 2019-09-11

やりたいこと

ユーザー情報のページのタイトルにユーザー名を表示したい。ページ読み込み時にユーザー情報をバックエンドから取得して、head の title に設定する。

結果

動いた.ts
  head: function() {
    return {
      title:`${this.$store.state.user.nickname}さんのプロフィール`
    }
  },
  async fetch({ store }) {
    // User を取得する
    await store.dispatch('user/getUser')
  }

ポイント

head は関数にする

以下のように関数にしないと store を参照できない様子。 Cannot read property '$store' of undefined というエラーが出ます。

ダメな実装例.ts

  head: {
    title:`${this.$store.state.user.nickname}さんのプロフィール`
  },

アロー関数を使わない

アロー関数を使うと Nuxt の this を参照できないので function() {} を使う

ダメな実装例.ts

  head: () => ({
    title:`${this.$store.state.user.nickname}さんのプロフィール`
  }),

^ の this は参照できません。

参考

https://github.com/nuxt/nuxt.js/issues/1086
https://github.com/nuxt/nuxt.js/issues/2536#issuecomment-356259396
https://qiita.com/_Keitaro_/items/d48733a19c10889e2365

3
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
3
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?