NuxtJSを触ってみる

公式: NUXT JS
Vue.js に基づいたプログレッシブフレームワーク
Universalモード、SPAモード、Generateモードの3つのモードで柔軟にサイトを設計できる

### 機能
– Vue ファイルで記述できること(*.vue)
– コードを自動的に分割すること
– サーバーサイドレンダリング
– 非同期データをハンドリングするパワフルなルーティング
– 静的ファイルの配信
– ES2015+ のトランスパイレーション
– JS と CSS のバンドル及びミニファイ化
– 要素の管理
– 開発モードにおけるホットリローディング
– プリプロセッサ: Sass, Less, Stylus など
– HTTP/2 push headers ready
– モジュール構造で拡張できること

### 動作
Vue2(Vue本体), Vue Router(Routing), Vuex(Vue版Flux), Vue Server Render(ServerSideレンダリング), Vue Meta(メタ情報管理)

### NuxtJSを始めよう
$ cat /etc/os-release
NAME=”Ubuntu”
VERSION=”18.04.4 LTS (Bionic Beaver)”
// 以下略

// npm, nodejsインストール
$ sudo apt install -y nodejs npm
$ node -v
v8.10.0
$ npm -v
3.5.2

// npmを最新化
$ sudo npm install npm@latest -g

$ sudo npm install -g vue-cli // sudo権限がないとエラーになる

$ vue init nuxt-community/starter-template sample
? Project name sample
? Project description Nuxt.js project
? Author hpscript

$ cd sample
$ ls
README.md components middleware package.json plugins store
assets layouts nuxt.config.js pages static
$ sudo npm install
$ sudo npm run dev

> sample@1.0.0 dev /home/vagrant/local/sample
> nuxt

FATAL Unexpected token { 13:12:14

} catch {
^

ん? nodeがv8.10.0では古いよう。
最新に上げます。

$ sudo npm install n -g
$ sudo n stable
$ sudo apt purge -y nodejs npm
$ exec $SHELL -l
$ node -v
v12.18.3
$ npm -v
6.14.6
$ sudo npm run dev

vagrantのprivate networkが192.168.33.10なので、
nust.config.jsのサーバの設定も変更する必要があります。

1
2
3
4
5
6
7
8
module.exports = {
  // 省略
  server: {
    port: 8000, // デフォルト: 3000
    host: '192.168.33.10' // デフォルト: localhost
  },
  // 省略
}

/pages/users/index.vue

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<template>
    <section class="container">
        <div>
            <h1>user index page</h1>
            <p>count={{count}}</p>
            <button @click="addCount">カウントアップ</button>
        </div>
    </section>
</template>
 
<script>
export default {
    computed: {
        count() { return this.$store.state.counter.count }
    },
    methods: {
        addCount(e){
            this.$store.commit('counter/add')
        }
    }
}
</script>

/store/counter.js

1
2
3
4
5
6
7
8
9
export const state = () => ({
    count: 0
})
 
export const mutations = {
    add (state){
        state.count += 1
    }
}