JSFiddle - React, Tailwind, and code Playground

by mizobata

HTML

<script src="//unpkg.com/vue/dist/vue.js"></script>
<div id="item-list-wrapper">
  <button
    id="prev"
    @click="prev"
  >
  ←
  </button>
  <div id="item-list" ref="itemList">
   <div id="item-group" ref="itemGroup" :style="{marginLeft: marginLeft + 'px'}">
      <div
        v-for="(item, index) in itemList"
        class="item"
      >
      {{item}}
      </div>
    </div>
  </div>
  <button
    id="next"
    @click="next"
  >
  →
  </button>
  <button @click="thaad">3rd</button>
  </button>
</div>

CSS

#item-list {
  border: 1px solid blue;
  width: 400px;
  overflow: hidden;
  white-space: nowrap;  
  padding: 5px;
}

.item {
  display: inline-block;
  border: 1px solid #000;

}

button {
  display: inline-block;
}

#item-group {
  transition: all .3s ease;
}

JavaScript

new Vue({
  el: '#item-list-wrapper',
  data: {
    currentItem: 0,
    marginLeft: 0,
    itemList: [
      'shop item1 item',
      'shop item2',
      'shop item3',
      'shop item4',
      'shop item5',
      'shop item6 item item',
      'shop item item'
    ],
    itemListWidth: 0,
  },
  
  mounted() {
  	console.log(this.$refs.itemList)
    this.itemListWidth = this.$refs.itemList.clientWidth
  },
  
  computed: {
    listLength() {
      return this.itemList.length
    }
  },
  
  methods: {
		prev(e) {
    	const moveWidth = this.$refs.itemGroup.children[this.currentItem].clientWidth
      
      const itemList = this.$refs.itemGroup.children
      let width = 0
      for (let i = this.currentItem; i < this.listLength; i++) {
        width += this.$refs.itemGroup.children[i].clientWidth
      }
      console.log(width, this.itemListWidth)
      if (width > this.itemListWidth) {
      	this.currentItem++
      	this.marginLeft -= moveWidth
      }
    },
    next(e) {
      if (this.currentItem !== 0) {
        this.currentItem--;
        const moveWidth = this.$refs.itemGroup.children[this.currentItem].clientWidth
        this.marginLeft += moveWidth
      }
    },
    thaad(e) {
      this.currentItem = 2;
      this.marginLeft = 0;
      
      for (let i = 0; i < this.currentItem; i++) {
        this.marginLeft -= this.$refs.itemGroup.children[i].clientWidth
      }
    }
  },
});