WordPress に Vue.js を スモールスタートで入れてみる その6
とあるサイトでVue.jsで作っていて、公開してからもろもろやったことまとめ その6
今回はPhotoSwipeのvueモジュールについて

v-photoswipe
バニラJSのフォトギャラリープラグイン PhotoSwipe
スワイプなど、スマホの各アクションにも対応しているのでlightbox系ではこれを最近よく使っています。
Vueモジュールでも用意されているのでそれを使います。
GitHub: Leesson/v-photoswipe: Vue plugin for image preview base on PhotoSwipe
npm: v-photoswipe - npm
最終的には前回のIsotopeと併用したので組み合わせが必要ですがPhotoSwipeのところだけ抜き出し
サムネイル部分は決まった形なので a要素に @click=“showPhotoSwipe(index)” をつけて data と methods も指定しておく。
v-photoswipe の items に フルサイズの画像もバインドしておく。
このフルサイズは形がきまっているので、下記のようになるよう調整しておく必要がある。
(fullsizes.forEach(function(v, i, a){… のところ)
items
[
{
"src":"https:\/\/siteUrl.com\/image01.jpg",
"w":1280,
"h":620
},
{
"src":"https:\/\/siteUrl.com\/image02.jpg",
"w":1280,
"h":620
}
]
sampleGallery.vue
<template>
<ul v-if="sampleGallery">
<li
:key="index"
v-for="(image, index) in sampleGallery"
>
<a
href="javascript:void(0);"
@click="showPhotoSwipe(index)"
>
<img
:src="image.sizes.thumbnail"
:width="image.sizes['thumbnail-width']"
:height="image.sizes['thumbnail-height']"
>
</a>
</li>
</ul>
<div>
<v-photoswipe
:isOpen="photoSwipeIsOpen"
:items="PhotoSwipeFullsizes"
:options="PhotoSwipeOptions"
@close="hidePhotoSwipe">
</v-photoswipe>
</div>
</template>
<script>
import { API_POST_URL } from './../variable'
import axios from 'axios';
import { PhotoSwipe } from 'v-photoswipe'
export default {
components: {
'v-photoswipe': PhotoSwipe
},
data() {
return {
sampleGallery: '',
// PhotoSwipe
photoSwipeIsOpen: false,
PhotoSwipeOptions: {
// ref: https://photoswipe.com/documentation/options.html
index: 0,
history: false,
bgOpacity: '.9',
preload: [1,3],
},
PhotoSwipeFullsizes: []
}
},
mounted() {
axios
.get(`${API_POST_URL}/POSTTYPE/${POST_ID}/`)
.then(response => {
this.sampleGallery = this.post.acf.sample_gallery
/*
* PhotoSwipe の画像を取得してdataに格納
*/
// フルサイズ
const fullsizes = response.data.sample_gallery_images
const fullsizeItems = []
fullsizes.forEach(function(v, i, a){
const fullsize = {
src: v[0], // 画像URL
w: v[1], // 横幅
h: v[2] // 縦幅
};
fullsizeItems.push(fullsize)
});
this.PhotoSwipeFullsizes = fullsizeItems
})
},
methods: {
// PhotoSwipe ギャラリー形式ではなくサムネイル + フルサイズの組み合わせで表示するメソッド
showPhotoSwipe (index) {
this.photoSwipeIsOpen = true
this.$set(this.PhotoSwipeOptions, 'index', index)
},
// PhotoSwipe クローズメソッド
hidePhotoSwipe () {
this.photoSwipeIsOpen = false
}
}
};
</script>