9
18

More than 3 years have passed since last update.

Nuxt.js入門

Last updated at Posted at 2020-07-11

nuxt入門

Nuxt.jsに入門してみましたので投稿します。

環境

Ubuntu(WSL Windows10 Home)を使っています。ここに作っていきます。

category value
platform Ubuntu 18.04.4 LTS (WSL)
Package Manager npm 6.14.4
JavaScript Node.js v12.17.0
frameworks @nuxt/cli v2.13.2
@nuxtjs/vuetify 1.11.2

準備

開発環境を作成するには、node.js, npmをインストールするだけです。

sudo apt install -y nodejs npm
sudo npm install n -g
sudo n stable
sudo apt purge -y nodejs npm

参考サイト: Ubuntuに最新のNode.jsを難なくインストールする

これで準備は完了しました。

Project作成

(1) npxでprojectを作成する

nuxtjsでは、npx create-nuxt-appでプロジェクトを作成します。いくつか質問をされますが、今回、私は以下のとおり選択してます。

npx create-nuxt-app nuxt-first-app
? Project name: nuxt-first-app
? Programming language: JavaScript
? Package manager: Npm
? UI framework: Vuetify.js
? Nuxt.js modules: Axios
? Linting tools: (Press <space> to select, <a> to toggle all, <i> to invert selection)
? Testing framework: None
? Rendering mode: Universal (SSR / SSG)
? Deployment target: Server (Node.js hosting)
? Development tools: jsconfig.json (Recommended for VS Code)

・・・・・しばらく時間がかかります。・・・・・

🎉  Successfully created project nuxt-first-app

(2) 起動

完了したら以下のコマンド実行して起動します。

cd nuxt-first-app
npm run dev

・・・・・しばらく時間がかかります。・・・・・

ℹ Waiting for file changes              
ℹ Memory usage: 423 MB (RSS: 533 MB)    
ℹ Listening on: http://localhost:3000/  

(3) 確認

起動できたら、http://localhost:3000/ にアクセスします。

image.png

Nuxt.jsでは、このプロジェクトをカスタマイズして自分用のアプリを作成していきます。

## 修正

warningは修正されており、現在(2021.01.30)では解消されていました。

warningがでてます。

WARN  [Vuetify] [UPGRADE] 'v-content' is deprecated, use 'v-main' 

warningなので必須ではないと思いますが気持ち悪いので修正しておきましょう。

### (1) projectのフォルダ・ファイル構成

修正するために、まずはプロジェクトのフォルダ・ファイル構成を確認しておきましょう。(READMEは省略)

├── assets
│   └── variables.scss
├── components
│   ├── Logo.vue
│   └── VuetifyLogo.vue
├── layouts
│   ├── default.vue
│   └── error.vue
├── middleware
├── pages
│   ├── index.vue
│   └── inspire.vue
├── plugins
├── static
│   ├── favicon.ico
│   ├── v.png
│   └── vuetify-logo.svg
├── store
├── jsconfig.json
├── nuxt.config.js
├── package-lock.json
└── package.json

### (2) 修正

この中で、「v-content」を含むファイルを探すと、「layouts/default.vue」(60行目付近)にありました。「v-content」を「v-main」に変更しておきます。

layouts/default.vue
<template>
・・・
-   <v-content>
+   <v-main>
      <v-container>
        <nuxt />
      </v-container>
-   </v-content>
+   </v-main>

### (3) 修正後の確認

再起動して確認し、warningが消えていたら成功です。

ページを追加する

ワーニングを修正したので、このプロジェクトをカスタマイズしてみましょう。公式ページに書いているように、Nuxt.js は pages ディレクトリ内の Vue ファイルの木構造に沿って、自動的に vue-router の設定を生成します。

ということで、pagesディレクトリのVueファイルを作成するだけでroutingが完了します。これはかなり便利です。

(1) ページを作成する

例として、pagesディレクトリの下に「about.vue」を作成し、以下のように編集します。

pages/about.vue
<template>
  <v-layout
    column
    justify-center
    align-center
  >
    <v-flex
      xs12
      sm8
      md6
    >
    <h1>about</h1>
    </v-flex>
  </v-layout>
</template>

(2) 確認

起動してhttp://localhost:3000/about にアクセスします。「about」が表示されればOKです。

とても簡単ですね。

画面遷移

ページを作成する方法が分かったので、次は画面にページ遷移を実装してみましょう。「layouts/default.vue」を開いて「<v-toolbar-title>」の下に以下のように編集してみます。

layouts/default.vue
<template>
  <v-app dark>
  ・・・
    <v-app-bar
      :clipped-left="clipped"
      fixed
      app
    >  
  ・・・
      <v-toolbar-title v-text="title" />
      <v-spacer />
      <nuxt-link to="/" class="ma-2">home</nuxt-link>      
      <nuxt-link to="/about" class="ma-2">about</nuxt-link> 
  ・・・

表示してみると、タイトルバーに「HOME」「ABOUT」のリンクボタンがあると思います。ボタンを押して画面に遷移できることを確認してみてください。これで画面遷移もOKです。

image.png

2021.01.30 add

Nuxt.js + FastAPIを使ったAPIの連携

フロントエンドに nuxt.js、バックエンドに FastAPIを使うアプリケーションを作成するときのnuxt.js側のcorsの解決方法やapiの呼び出し方法です。

Environment

wslにインストールしているubuntuなど環境はバージョンアップしています。

category
platform Ubuntu 20.04.1 LTS(WSL2)
Python 3.8.5
frameworks @nuxt/cli v2.14.12
fastapi 0.61.2

Webアプリケーションのイメージ

image.png

プロジェクトの構成

プロジェクトの直下は、client, serverというディレクトリを作成してそれぞれnuxt.js, FastAPIを作成していく。

directories,files
project
├── client
│    ・・・・
└── server
     ・・・・

client side

(1) プロジェクトの作成

nuxtのプロジェクトはnpx create-nuxt-app コマンドで作成する。質問では、JavaScript, Axios, SSRを選択する。以下のような感じです。

console
npx create-nuxt-app client
? Project name: client
? Programming language: JavaScript
? Package manager: Npm
? UI framework: Vuetify.js
? Nuxt.js modules: Axios - Promise based HTTP client
? Linting tools: (Press <space> to select, <a> to toggle all, <i> to invert selection)
? Testing framework: None
? Rendering mode: Universal (SSR / SSG)
? Deployment target: Server (Node.js hosting)
? Development tools: (Press <space> to select, <a> to toggl
e all, <i> to invert selection)
? What is your GitHub username? tadaharu-ishibe
? Version control system: 
  Git 
❯ None
# ・・・・
🎉  Successfully created project client

カレントを移動します。

cd client

(2) CORS (Cross-Origin Resource Sharing) を回避する

server sideでfastapiを使うためcorsに対応しておきます。

  • ① @nuxtjs/proxyのインストール
console
npm install @nuxtjs/proxy --save
  • ② nuxt.config.jsに@nuxtjs/proxyを追加する

nuxt.config.js ファイルのmodules, axios, proxyパラメータを下記のように設定する。fastapiのurlは、http://localhost:8000/api/ を想定する

nuxt.config.js
modules: [
    '@nuxtjs/axios',
    '@nuxtjs/proxy'
],
axios: {
    prefix: '/api',
},
proxy: {
'/api': {
    target: 'http://localhost:8000',
    pathRewrite: {
    '^/api': '/'
    }
}
},

(3) serverと連携するページを作成する

ボタンを押すと、APIを呼び出して画面上に表示するページを作成します。pages/index.vueを、以下のソースで書き換えます。

index.vue
<template>
  <div>
    <button v-on:click="showMessage">ボタン</button>
    <p> message : {{ message }} </p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: ""
    };
  },
  methods: {
    showMessage() {
      const response = this.$axios.$get("/api/hello")
        .then(response => {
          this.message = response
        })
        .catch(error => {
          console.log(error);
        })
    }
  }
}
</script>

以上でNuxt.jsの編集は完了。Nuxt.jsを起動しておく。

npm run dev

server side

FastAPIは手動でファイルを編集していきます。 serverフォルダの下にmain.pyを作成します。

directories,files
project
├── client
│    ・・・・
└── server
     main.py
console
mkdir server && cd server && touch main.py
main.py
from fastapi import FastAPI

app = FastAPI()

@app.get("/api/hello")
def read_root():
    return {"Hello": "World"}

以上でFastAPIの編集は完了。

起動する

uvicorn main:app

確認する

ブラウザからhttp://127.0.0.1:3000/にアクセスして「ボタン」を押すと「message : { "Hello": "World" }」が表示される。

まとめ

この辺で入門については終わります。WEBアプリケーションを簡単に作成できます。Nuxt.jsは非常にいいですね。

9
18
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
9
18