【Nuxt.js】画像モーダルでギャラリー表示

パッケージを入れる

npm install vue-light-gallery

Pluginファイル作成

  • plugins/lightGallery.client.js
import Vue from "vue";
import VueLightGallery from "vue-light-gallery";

Vue.use(VueLightGallery);

Nuxt.config.jsにPlugin追加

  • nuxt.config.js
  plugins: [
    // ...(省略)
    {src: "~/plugins/lightGallery.client.js", ssr: false } // 追加
  ],

使ってみる

<template>
  <div>
    <!-- サムネイル -->
    <div class="thumbnail-list">
      <img :src="path"
         class="thumbnail-list__img"
         v-for="(path, index) of thumb_image_paths"
         @click="activeImgIndex = index"
      />
  </div>
  <!-- /サムネイル -->

  <!-- 画像モーダル -->
  <LightGallery
    :images="image_paths"
    :index="activeFileIndex"
    :disable-scroll="true"
    @close="activeImgIndex = null"
  />
  <!-- /画像モーダル -->
</template>

<script>
export default {
  data() {
    return {
      image_paths: ['http://example.com/img1.jpg', 'http://example.com/img2.jpg', 'http://example.com/img3.jpg'],
      thumb_image_paths: ['http://example.com/img1-small.jpg', 'http://example.com/img1-small.jpg', 'http://example.com/img3-small.jpg'],
      activeImgIndex: null,
    }
  },
}
</script>

<style>
.thumbnail-list {
  display: flex;
  gap: 10px;
}

.thumbnail-list .thumbnail-list__img {
  width: 32%;
  aspect-ratio: 1 / 1;
  object-fit: cover;
  border-radius: 8px;
  cursor: pointer;
}
</style>

ざっくり補足
  • .thumbnail-list はサムネイルの一覧で、
    dataで設定したthumb_image_paths(=サムネイルファイルパスの配列)をループして表示してる
    ここの @click="activeImgIndex = index" によって
    画像モーダルにてアクティブにする画像のindexが設定される
  • 画像モーダルを表示するLightGalleryには
    dataで設定したimage_paths(=ファイルパスの配列)をpropsで渡してる
    また:indexアクティブになった画像のindexを渡すことでサムネイルのクリックと連動させている仕組み
  • LightGalleryでは画像タイトルも設定できる。設定したい場合はdataを下記のように変更する
data() {
    return {
      image_paths: [
        { title: 'image 1', url: 'http://example.com/img1.jpg' },
        { title: 'image 2', url: 'http://example.com/img2.jpg' },
        { title: 'image 3', url: 'http://example.com/img3.jpg' },
      ],
      thumb_image_paths: ['サムネファイルパス1', 'サムネファイルパス2', 'サムネファイルパス3'],
      activeImgIndex: null,
    }
  },
  • サムネイルとモーダル画像が同じ場合はサムネイルのthumb_image_pathsimage_pathsに変えてあげればOK

\ 案件のご依頼・ご相談はこちらから /