Re:ゼロから始める文系プログラマ

未経験がプログラミングを通して人生を変える

Nuxtjsで簡単なログインアプリを開発


スポンサードリンク
 

f:id:ShotaNukumizu_1000:20211114053051p:plain

おはようございます。Shotaです。

今回の記事では、VueのフレームワークNuxtjsを使って簡単なログインアプリを実装します。

😥「Nuxtについてイマイチわからない...」

このように考えている方は以下の記事にアクセスしてください。

▼おすすめの記事

shotanukumizu-1000.hatenablog.com

それでは早速、本題に入りましょう。

【注意】

本記事では、nuxt/authを使った実装を行っていません。(nuxt/authを使うとなるとJWT認証が必要になり、別でバックサイドを構築する必要があるからです)

今回はNuxtの基本を確認するという目的で非常に簡単なログインアプリを実装するのでご了承ください。



Nuxtのインストール

npm init nuxt-app <project-name>

上記の<project-name>については自由に名前をつけてもらっても構いません。


最初のページの作成

cd <project-name>
npm run dev

これで正常にhttp://localhost:3000/にアクセスできればインストール完了です。


「Hello Nuxt.js」の表示

pagesディレクトリにindex.vueを作ります。

<template>
  <div class="container">
    <h1>Hello Nuxt.js</h1>
    <nuxt-link to="/login">Log Out</nuxt-link>
  </div>
</template>

<script>
export default {}
</script>


ログイン機能の実装

ここからログイン機能を簡単に実装していきます。

それにあたって行う具体的な手順は以下の通りです。

  • ログインページの作成

  • ストア(store)の用意

  • index.jsの修正

  • nuxt.config.jsの修正


それぞれ順番に解説していきます。


ログインページの作成

<template>
    <div class="container">
        <form @submit.prevent="login">
            <p class="error" v-if="formError">{{ formError }}</p>
            <p>name: <input type="text" v-model="formUsername" name="username"></p>
            <p>password: <input type="text" v-model="formPassword" name="password"></p>
            <button type="submit">Login</button>
        </form>
    </div>
</template>

<script>
export default {
    data() {
        return {
            formError: null,
            formUsername: 'demo',
            formPassword: 'password0',
        }
    },
    methods: {
        async login() {
            try {
                await this.$store.dispatch('login',{
                    username: this.formUsername,
                    password: this.formPassword
                })
                this.$router.push('/')
            } catch (error) {
                this.formError = error.message
            }
        }
    },
}
</script>


ストア(store)の用意

Vueでグローバルなステート(サイトの状態)を管理するために、Vuexが用意されています。

storeディレクトリにindex.jsを作成します。

export const state = () => ({
    authUser: null,
})

export const mutations = {
    SET_USER: function(state, data) {
        if (data) {
            state.authUser = data
        } else {
            state.authUser = null
        }
    }
}

export const actions = {
    async login({ commit }, { username, password }) {
        try {
            if (username != "demo" || password != "password0") {
                throw new Error("error!")
            }
            commit('SET_USER', username)
        } catch (error) {
            throw error
        }
    },
    async logout({ commit }) {
        try {
            commit('SET_USER', null)
        } catch (error) {
            throw error
        }
    }
}


index.jsの修正

ログアウトボタンをここで追加します。

<template>
  <div class="container">
    <h1>Hello Nuxt.js</h1>
    <nuxt-link to="/login">Log Out</nuxt-link>
  </div>
</template>

<script>
export default {}
</script>


middlewareの設定

Nuxtjsでは、あるページがレンダリングされる前に実行される関数を、middlewareで実装できますので、これを使って各ページの認証を行います。

middlewareディレクトリにauth.jsを作成します。この際、空のままにしておきましょう。ストアのauthUserが空だった場合は、/loginに遷移します。


nuxt.config.jsの修正

export default {
  // Global page headers: https://go.nuxtjs.dev/config-head
  head: {
    title: 'loginapp',
    htmlAttrs: {
      lang: 'en'
    },
    meta: [
      { charset: 'utf-8' },
      { name: 'viewport', content: 'width=device-width, initial-scale=1' },
      { hid: 'description', name: 'description', content: '' },
      { name: 'format-detection', content: 'telephone=no' }
    ],
    link: [
      { rel: 'icon', type: 'image/x-icon', href: '/favicon.ico' }
    ]
  },

  // Global CSS: https://go.nuxtjs.dev/config-css
  css: [
  ],

  // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins
  plugins: [
  ],

  // Auto import components: https://go.nuxtjs.dev/config-components
  components: true,

  // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules
  buildModules: [
    // https://go.nuxtjs.dev/eslint
    '@nuxtjs/eslint-module'
  ],

  // Modules: https://go.nuxtjs.dev/config-modules
  modules: [
    // https://go.nuxtjs.dev/axios
    '@nuxtjs/axios',
    '@nuxtjs/auth',
  ],

  // Axios module configuration: https://go.nuxtjs.dev/config-axios
  axios: {},

  // Build Configuration: https://go.nuxtjs.dev/config-build
  build: {
  },
  // 追加
  router: {
    middleware: 'auth'
  }
}


起動及び挙動の確認

npm run dev

ログアウトした状態で/indexにアクセスしても、無事/loginに戻れますね。


まとめ

今回の記事では、auth/userを使わずにNuxtjsで簡単なログインアプリを買いはつする方法を解説しました。

今回の記事を参考に、Nuxtjsに対する理解を深めていただければ幸いです。

今回の記事はこれで終了です。

【参考サイト】

blog.keepdata.jp

ソースコード

github.com