Nuxt.jsとElementUIを組み合わせて使う


経緯

ReactのNext.jsが2系の時代にちょっと使ってみたもののCSSまわりが馴染めず(当時外部ファイルでグローバルCSSを管理したかった)だいぶ放置してしまっていたところ、Vue.jsのNuxt.jsで1系(RC版)が出ていることに気づいたので試してみることに。

せっかくなので、良さげなUIライブラリのElementも使ってみよう。

Nuxt.js?

サーバサイドレンダリングやルーティングが楽にできるVue.jsのライブラリ(と捉えている)。
ReactのNext.jsに対して、Vue.jsのNuxt.js。

ElementUI?

グリッドレイアウトからボタン・タブなどのUI、フォーム要素、ダイアログ、ツールチップ、ローディングまでいろいろ揃ってるVue.js向けUIライブラリ。
これがあればjQueryライクにVue.jsを使いながら、整ったレイアウトやUIを作り込めるのではないか(と期待している)。

手順

Nuxt.jsのインストール

npm i nuxt -S

package.jsonは以下のようになっている(nuxt 1.4.0)。

package.json
{
  "name": "nuxt+element",
  "version": "1.0.0",
  "description": "",
  "main": "nuxt.config.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "nuxt": "nuxt"
  },
  "keywords": [],
  "author": "teriyakisan",
  "license": "ISC",
  "dependencies": {
    "nuxt": "^1.4.0"
  }
}

Elementのインストール

npm init -y
npm i element-ui -S

Nuxt.jsのプラグインとして使うため、plugins/element-ui.jsnuxt.config.jsを作成。

plugins/element-ui.js
import Vue from 'vue'
import ElementUI from 'element-ui'
import locale from 'element-ui/lib/locale/lang/ja'

Vue.use(ElementUI, { locale })
nuxt.config.js
module.exports = {
  build: {
    vendor: ['element-ui']
  },
  plugins: [
    '~plugins/element-ui'
  ],
  css: [
    'element-ui/lib/theme-chalk/index.css'
  ]
}

サーバ起動。

npm run nuxt

ページを作成

pages/index.vueを作成
ElementのRateコンポーネントを使ったサンプルを記述。
なんとなく★の色がNuxt.jsカラーになるようにしておく。

pages/index.vue
<template>
  <div>
    <div class="block">
      <h4>Nuxt.js + Element?</h4>
      <el-rate v-model="value" :colors="['#2F3D4D', '#64B486', '#4B7C6E']"></el-rate>
    </div>
  </div>
</template>

<style scoped>
  .block {
    padding: 0 20px;
  }
</style>

<script>
export default {
  data () {
    return {
      value: null
    }
  }
}
</script>

ブラウザで確認

いい感じ!