Nuxt.js ライブラリ「vue-load-image」をインストールしてローダーを表示する

Nuxt.js ライブラリ「vue-load-image」をインストールしてローダーを表示する

ライブラリ「vue-load-image」をインストールすると、ローダーの実装が簡単に可能です。ここでは、nuxt.jsでvue-load-imageを利用するための手順と簡単な使い方を記述してます。

環境

  • OS  CentOS Linux release 8.0.1905 (Core)
  • node V12.16.3
  • npm 6.14.4
  • nuxt 2.12.2

Nuxt.js環境構築

下記のコマンドで構築。ここでは、nuxtappという名前でプロジェクトを作成してます。

npx create-nuxt-app nuxtapp

ここでは、下記の設定で構築してます。

create-nuxt-app v2.15.0
✨  Generating Nuxt.js project in testnuxt
? Project name nuxtapp
? Project description My doozie Nuxt.js project
? Author name 
? Choose programming language JavaScript
? Choose the package manager Yarn
? Choose UI framework None
? Choose custom server framework None (Recommended)
? Choose Nuxt.js modules (Press <space> to select, <a> to toggle all, <i> to invert selection)
? Choose linting tools ESLint
? Choose test framework None
? Choose rendering mode Universal (SSR)
? Choose development tools (Press <space> to select, <a> to toggle all, <i> to invert selection)
yarn run v1.22.4

※yarnをインスールしているので、ここではnpmではなくyarnを選択してます。

## yarnのインスールは下記コマンド
npm install -g yarn

外部IP許可

localhostではなくプライベートIPを利用して接続して確認したいので、作成したプロジェクトnuxtappの配下にあるpackage.jsonに下記を追加します。

"config": {
  "nuxt": {
    "host": "0.0.0.0",
    "port": "3000"
  }
},

vue-load-imageインストール

下記のコマンドでインストールします。

## 作成したプロジェクトに移動
cd nuxtapp

## インストール
yarn add vue-load-image

vue-load-image使い方

plugins配下にplugin.jsを作成し、下記の通りに編集します。

import Vue from 'vue'
import VueLoadImage from 'vue-load-image'
Vue.use(VueLoadImage)

プロジェクト配下にあるnuxt.config.jsに下記のコードを追加します。

plugins: [
    {
      src: '@/plugins/plugin',
      mode: 'client'
    }
  ],

pages配下にあるindex.vueを下記の通りに編集します。

<template>
  <div class="container">
    <h1>vue-load-image</h1>
    <button @click="changeImageURL">change image</button>
    <vue-load-image>
      <img slot="image" :src="src" />
      <img src="~assets/image-loader.gif" slot="preloader" />      
      <div slot="error">error message</div>
    </vue-load-image>
  </div>
</template>

<script>
export default {
  components: {
  },
  data() {
    return {     
      src: "https://picsum.photos/500/600/?random"
    }
  },
  methods: {
    changeImageURL() {
      const randomImageNumber = Math.floor(Math.random() * 999) + 1;
      this.src = "https://picsum.photos/500/600/?image=" + randomImageNumber;
    }
  }
}
</script>

<style>
.container {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  color: #2c3e50;
  margin: 60px 0px 0px 60px;
}
button {
  height: 35px;
  font-size: 16px;
  border-radius: 6px;
  margin-bottom: 12px;
  -webkit-appearance: none;
}
</style>

起動します

yarn dev

ブラウザから http://プライベートIP:3000にアクセスすると、ローダーが表示されていることが確認できます。