はじめに
今回は、Vue.jsを使って画像のスライドショーを作成してみます。
準備
Vue.jsのプロジェクトをセットアップする
今回は、Vue CLIを使用します。
Vue CLIのインストール
Vue CLIがインストールされていない場合は、以下のコマンドでインストールします。npm install -g @vue/cli
新しいVueプロジェクトの作成
Vue CLIを使って新しいプロジェクトを作成します。vue create <your-project-name>
コマンド実行時にいくつか質問されます。お好みの設定にしてください。
依存関係をインストールし、開発サーバーを起動する
作成した新しいプロジェクトに移動し、コマンドを実行します。cd <your-project-name> npm install npm run serve
プレイグラウンド環境
Vue SFC Playground を使うと手軽にVueを始められるのでおすすめです。
https://ja.vuejs.org/guide/quick-start#try-vue-online
実装
画像スライドショーのコンポーネントを作成する
画像のスライドを行うコンポーネント、src\components\Slideshow.vue を作成します。
複数の画像を順に表示、ナビゲーションボタンを押下で前後の画像にスライドできるようにします。
Slideshow.vue
<template>
<div class="slideshow">
<img :src="images[currentIndex]" class="slide-image" />
<button @click="prevSlide" class="nav-button prev-button">‹</button>
<button @click="nextSlide" class="nav-button next-button">›</button>
</div>
</template>
<script>
export default {
data() {
return {
// 表示中のスライドのインデックス
currentIndex: 0,
// 表示する画像のリスト
images: [
'{Image1のパス}',
'{Image2のパス}',
'{Image3のパス}',
'{Image4のパス}',
]
};
},
methods: {
// 前のスライドを表示する
prevSlide() {
this.currentIndex = (this.currentIndex == 0) ? this.images.length - 1 : this.currentIndex - 1;
},
// 次のスライドを表示する
nextSlide() {
this.currentIndex = (this.currentIndex == this.images.length - 1) ? 0 : this.currentIndex + 1;
}
}
};
</script>
<style scoped>
.slideshow {
width: 500px;
position: relative;
}
.slide-image {
width: 100%;
height: auto;
}
.nav-button {
border: none;
background-color: #6699cc;
color: #fff;
position: absolute;
top: 50%;
transform: translateY(-50%);
padding: 10px;
cursor: pointer;
}
.prev-button {
left: 0;
}
.next-button {
right: 0;
}
</style>
App.vue からコンポーネントを呼び出す
Slideshow.vue
コンポーネントを使用するよう、App.vue
ファイルを書き換えます。
vue
<template>
<div id="app">
<Slideshow />
</div>
</template>
<script>
// Slideshow.vueをインポート
import Slideshow from './components/Slideshow.vue';
export default {
components: {
Slideshow
}
};
</script>
実際に動かしてみる
以下のコマンドを実行しプロジェクトを実行します。
npm run dev
リストの一番先頭のスライドが表示されます。
「>」押下で Image2 へ遷移、
「<」押下で Image4 へ遷移します。
最後に
今回は、Vue.jsを使って画像のスライドショーを作成してみました。
スライドの自動再生や、各スライドのサムネイル表示など拡張の余地があるので、今後試していきたいと思います。
ご覧いただきありがとうございました。