Help us understand the problem. What is going on with this article?

Vue.jsでカルーセルをつくる

More than 1 year has passed since last update.

自前でVue.jsのカルーセルを作成したい人向け。

サンプル

https://jsfiddle.net/Wave7KN/ejm664m1/5/

vue-carousel.png

コード

HTML
<div id="vue-carousel" class="vue-carousel">

  <!-- スライドする部分。keyを持たせることで、それぞれが個別の要素であることを示す。 -->
  <transition :name="transition_name">
    <div class="vue-carousel_body"
      :key="index"
      v-for="(content, index) in contents"
      v-if="visible_content == index"
      :style="{backgroundColor: content.bg_color}">
      {{ content.title }}
    </div>
  </transition>

  <!-- 「PREV」「NEXT」と現在地のドット -->
  <div class="vue-carousel_footer">
    <button @click="back()" :disabled="visible_content == 0">PREV</button>
    <div class="vue-carousel_footer_dot"
      v-for="(contents, index) in contents"
      :class="{'is-visible' : visible_content == index}"></div>
    <button @click="next()" :disabled="visible_content == contents.length - 1">NEXT</button>
  </div>

</div>

JavaScript
new Vue({
  el: '#vue-carousel',
  data: {
    contents: [{
      // 青の中身
      title: 'Content 1',
      bg_color: '#7bbff9',
    },{
      // 赤の中身
      title: 'Content 2',
      bg_color: '#f16972',
    },{
      // 緑の中身
      title: 'Content 3',
      bg_color: '#20d2a3',
    }],
    transition_name: 'show-next',
    visible_content: 0,
  },
  methods: {
    back(){
      this.transition_name = 'show-prev';
      this.visible_content--;
    },
    next(){
      this.transition_name = 'show-next';
      this.visible_content++;
    },
  },
})
SCSS
.vue-carousel{
  height: 200px;
  overflow: hidden;
  position: relative;
  width: 300px;
  &_body{
    color: #fff;
    height: 150px;
    left: 0;
    line-height: 150px;
    position: absolute;
    text-align: center;
    top: 0;
    width: 100%;    
  }
  &_footer{
    align-items: center;
    display: flex;
    height: 50px;
    justify-content: space-between;
    position: absolute;
    top: 150px;
    width: 100%;
    &_dot{
    background-color: #abc2ce;
      border-radius: 50%;
      height: 6px;
      width: 6px;
      &.is-visible{
        background-color: #7b94f9;
      }
    }
  }
}

// 進むトランジションと戻るトランジションをそれぞれ用意
.show-next-enter-active, .show-next-leave-active,
.show-prev-enter-active, .show-prev-leave-active  {
  transition: all .4s;
}
.show-next-enter, .show-prev-leave-to {
  transform: translateX(100%);
}
.show-next-leave-to, .show-prev-enter {
  transform: translateX(-100%);
}

参考

Enter/Leave とトランジション一覧
https://jp.vuejs.org/v2/guide/transitions.html

Wave7KN
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away