vue.js 2 - vuetify - carousel

My P·2023년 2월 23일
0

드래그 기능 추가 코드


<template>
  <div id="app">
    <v-app id="vapp">
      <v-carousel ref="myCarousel" hide-delimiters :touchless="true">
        <v-carousel-item v-for="(item,i) in items" :key="i" :src="item.src"></v-carousel-item>
      </v-carousel>
    </v-app>
  </div>
</template>

<script>
export default{
  data() {
      return {
        move: [],
        drag: false,
        touch: false,
        items: [
          {
            src: "https://cdn.vuetifyjs.com/images/carousel/squirrel.jpg"
          },
          {
            src: "https://cdn.vuetifyjs.com/images/carousel/sky.jpg"
          },
          {
            src: "https://cdn.vuetifyjs.com/images/carousel/bird.jpg"
          },
          {
            src: "https://cdn.vuetifyjs.com/images/carousel/planet.jpg"
          }
        ]
      };
    },
    methods: {
      logic(e) {
        const currentMove = this.touch ? e.touches[0].clientX : e.clientX;
        if (this.move.length === 0) {
          this.move.push(currentMove);
        }
        if (this.move[this.move.length - 1] - currentMove < -100) {
          this.$refs.myCarousel.$el
            .querySelector(".v-window__prev")
            .querySelector(".v-btn")
            .click();
          this.drag = false;
          this.touch = false;
        }
        if (this.move[this.move.length - 1] - currentMove > 100) {
          this.$refs.myCarousel.$el
            .querySelector(".v-window__next")
            .querySelector(".v-btn")
            .click();
          this.drag = false;
          this.touch = false;
        }
      }
    },
    mounted() {
      // For touch devices
      this.$refs.myCarousel.$el.addEventListener("touchmove", (e) => {
        this.drag = false;
        this.touch = true;
        this.logic(e);
      });
      window.addEventListener("touchend", (e) => {
        this.move = [];
      });

      // For non-touch devices
      this.$refs.myCarousel.$el.addEventListener("mousedown", (e) => {
        this.drag = true;
        this.touch = false;
        this.logic(e);
      });
      this.$refs.myCarousel.$el.addEventListener("mousemove", (e) => {
        this.drag && this.logic(e);
      });
      window.addEventListener("mouseup", (e) => {
        this.drag = false;
        this.touch = false;
        this.move = [];
      });
    }
}
</script>
profile
박문

0개의 댓글