vue组件Better-Scroll基本用法

vue组件Better-Scroll基本用法


安装:

npm install better-scroll

真接上例子:

<template>
  <div class="wrapper">
    <div ref="content" class="content">
        <div ref="card" class="card" v-for="(card, index) in cards" :key="index">
          <b class="close_icon" @click="deleteCard(card)">x</b>
          <p>{{card.name}}</p>
        </div>
    </div>
  </div>
</template>

<script>
import BScroll from 'better-scroll'

export default {
  name: 'HelloWorld',
  data() {
    return {
      cards: [
        {name: 'a', id: 1},
        {name: 'b', id: 2},
        {name: 'c', id: 3},
        {name: 'd', id: 4},
        {name: 'e', id: 5},
        {name: 'f', id: 6},
        {name: 'g', id: 7},
        {name: 'h', id: 8},
        {name: 'i', id: 9},
        {name: 'j', id: 10},
        {name: 'l', id: 11},
        {name: 'm', id: 12},
        {name: 'n', id: 13},
        {name: 'o', id: 14}
      ]
    }
  },
  created() {
  	// 初始化better-scroll
    this.$nextTick(() => {
      this.initScroll()
    })
  },
  mounted() {
  	// 初始化容器大小
    this.initContentWidth()
  },
  watch: {
  	// 监视data数据变化,动态改变容器大小
    cards() {
      this.initContentWidth()
    }
  },
  methods: {
    initContentWidth() {
      let content = this.$refs.content;
      let card = this.$refs.card;
      // 每个item默认宽度为100
      let defaultWidth = 100;
      // 如果只有一个元素 通过 this.$refs获取的就不是一个数组,所以要判断
      if (card.length) {
        defaultWidth = card[0].offsetWidth
      } else {
        defaultWidth = card.offsetWidth
      }
      // 2是2px的边框
      content.style.width = (defaultWidth + 2) * this.cards.length + 'px'
    },
    initScroll() {
      new BScroll('.wrapper', {
        scrollX: true,
        click: true
      })
    },
    deleteCard(card) {
      let index = this.cards.indexOf(card);
      if (index !== -1) {
        this.cards.splice(index, 1);
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.wrapper {
  height: 160px;
  overflow: hidden;
  border: 1px solid red;
}
.content {
  height: 100%;
}
.card {
  height: 95%;
  width: 100px;
  border: 1px solid blue;
  position: relative;
  display: inline-block;
}
.close_icon {
  display: inline-block;
  position: absolute;
  right: 10px;
  top: 5px;
  border: 1px solid red;
}
</style>

你可能感兴趣的:(前端,Vue)