5
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 3 years have passed since last update.

【Nuxt/Composition API】Cannot read property '$auth' of undefined の解決法

Posted at

はじめに

@nuxt/authを使ってログイン認証をしようとしていたがエラーが出て詰まったのでメモ。
※ めちゃくちゃ初歩的なミスです。

環境

"nuxt": "^2.14.6",
"@vue/composition-api": "^1.0.0-beta.20",
"@nuxtjs/auth": "^4.9.1"

問題のコード

onSubmitButtonClickでリクエストを送りたい

signIn.vue
<script lang="ts">
import { defineComponent, reactive, ref } from '@vue/composition-api'
export default defineComponent({
  setup() {
    const email = ref('')
    const password = ref('')
    const onSubmitButtonClick = (e: Event) => {
      this.$auth
        .loginWith('local', {
          // emailとpasswordの情報を送信
          data: {
            email: email,
            password: password,
          },
        })
        .then(
          (res:any) => {
            // 認証成功後に実行したい処理
          },
          (e: Error) => {
            // 失敗時の処理
          }
        )
    }
    return { email, password, onSubmitButtonClick }
  },
})
</script>
nuxt.config.ts
export default {
  ...
  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/auth'
  ],
  ...
}
tsconfig.json
{
  ...
  "types": [
    "@types/node",
    "@nuxt/types",
    "@nuxtjs/axios",
    "@nuxtjs/auth",
  ],
  ...
}

エラーメッセージ

Cannot read property '$auth' of undefined

nuxt.config.tsの設定もしてるのになぜ、、、

解決法

composition APIの理解の甘さでした。
Vue 2.xまでthis.$~で取得していたものは、compositionAPIではsetup関数の第二引数であるcontextから取得する様変更された様です。

公式ドキュメントにもありました。

The second argument provides a context object which exposes a selective list of properties that were previously exposed on this in 2.x APIs:


const MyComponent = {
  setup(props, context) {
    context.attrs
    context.slots
    context.emit
  }
}

今回の場合は

this.$authcontext.root.$auth

に変更した所、解決しました。

signIn.vue
setup(_props, context) {
...
  const onSubmitButtonClick = (e: Event) => {
    context.root.$auth.loginWith('local', {
...

まとめ

今回はcompositionAPIもnuxtも理解が曖昧なまま進めた結果詰まってしまいました、、
勿体ないのでインプットも丁寧にしていきたい。


Twitterやってるのでフォローお願いします!
https://twitter.com/1keiuu

5
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
5
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?