Vue滚动插件 vue-horizontal

359 阅读1分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第2天,点击查看活动详情

今天新接了一个业务需求,一个列表中需要横向点击按钮滚动,当内容没超出父盒子的时候滚动按钮不显示,没发生滚动时左边按钮不显示,滚动到底时右边按钮不显示。

在思考怎么做的时候,考虑过获取元素滚动距离,通过点击事件js改变滚动距离,判断滚动距离来隐藏和显示滚动按钮。

实践中发现不太好做,工作量比较大(也可能是我比较菜,有更好的思路可以评论区告诉我)

然后就在百度上找到了 vue-horizontal这个插件,滚动非常丝滑,灵活性很高,可以自由进行魔改样式

首先安装

//npm 安装
npm i vue-horizontal
​
//yarn 安装
yarn add vue-horizontal
​
​
//脚本引入
<!-- without version -->
<script src="https://cdn.jsdelivr.net/npm/vue-horizontal/dist/vue-horizontal.esm.min.js"></script><!-- with version, go https://www.jsdelivr.com/package/npm/vue-horizontal to find -->
<script src="https://cdn.jsdelivr.net/npm/vue-horizontal@0.x.x/dist/vue-horizontal.esm.min.js"></script>

顾名思义是专门给vue用的,react和html原生页面暂不支持,因为需要用到vue组件

vue全局安装

import Vue from 'vue';
import VueHorizontal from 'vue-horizontal';
​
Vue.use(VueHorizontal);
​
//这样就可以在任何页面中使用
    <vue-horizontal>
      <!-- ... -->
    </vue-horizontal>
//来使用滚动

如果只有一个页面或者两个页面使用到的话,可以使用局部引入

<template>
  <div>
    <vue-horizontal>
      <!-- ... -->
    </vue-horizontal>
  </div>
</template><script>
import VueHorizontal from 'vue-horizontal';
​
export default {
  components: {VueHorizontal},
  //...
}
</script>

ok,安装完毕,现在开始使用

<template>
  <vue-horizontal responsive>
    <section v-for="item in items" :key="item.i">
      <h4>{{ item.title }}</h4>
      <p>{{ item.content }}</p>
    </section>
  </vue-horizontal>
</template>
<script>
export default {
  data() {
    return {
      // E.g: creates 20 array items...
      items: [...Array(20).keys()].map((i) => {
        return {i, title: `Responsive`, content: `Content`};
      }),
    }
  }
}
</script>
<style scoped>
section {
  padding: 16px 24px;
  background: #f3f3f3;
}
</style>

我们可以看到,需要在vue-horizontal组件标签中使用section来放入需要循环的数据,值得注意的是,需要在组件标签中加入responsive来使css样式可以被编辑,这样section的样式就可以随意更改了

我们还能通过插槽的方式来改变滚动按钮

<template>
  <vue-horizontal responsive class="horizontal" :displacement="0.7">
    <template v-slot:btn-next>
      <div class="replaced-btn">
        <div>MORE</div>
      </div>
    </template>
​
    <placeholder-component v-for="i in [0,1,2,3,4,5,6,7,8,9,10,11,12]" :key="i">
      {{ i }}
    </placeholder-component>
  </vue-horizontal>
</template>

\