Nuxt内で複数のtableの横スクロールを同時に制御する事がありましたのでそのやり方を残しておきます。
vue-scroll-synとは?
複数のスクロールバーを連動させるにはvue-scroll-sync
のライブラリーを使用します。
こちらを使えば縦、横それぞれのスクロールを連動できます。
vue-scroll-syn
インストール
yarn
yarnからインストール
yarn add vue-scroll-sync
npm
npmからインストールする
npm i --save vue-scroll-sync
gitリポジトリはこちら
https://github.com/metawin-m/vue-scroll-sync?ref=kabanoki.net
ライブラリーの読み込み
単一で読み込む場合は直接importで読み込ませ、
<scroll-sync></scroll-sync>
で囲えば使えます。
<template>
<scroll-sync>
Content
</scroll-sync>
</template>
<script>
import ScrollSync from 'vue-scroll-sync';
</script>
plugin化する
プラグインでまとめる場合はこのようにします。
import Vue from 'vue'
import ScrollSync from 'vue-scroll-sync'
Vue.component('scroll-sync', ScrollSync)
nuxt.config.jsにプラグインを読み込ませます。
module.exports = {
// 省略
plugins: ['~plugins/vue-scroll-sync']
// 省略
}
スクロール位置
縦方向の連動を行う場合verticalを設定します。
横方向の連動を行う場合horizontalを設定します。
<template>
<div>
<!-- 縦方向 -->
<scroll-sync vertical>
Content
</scroll-sync>
<!-- 横方向 -->
<scroll-sync horizontal>
Content
</scroll-sync>
</div>
</template>
サンプル
実際にtableで縦横固定ヘッダーでどのような動きになるのかサンプルを作って見ました。
<template>
<div>
<scroll-sync
class="table-wrap"
v-for="tw of 5"
:key="tw"
vertical
horizontal
>
<table class="table">
<thead class="thead" v-if="tw===1">
<tr>
<template v-for="n of 10">
<th
class="item"
:key="n"
v-if="n===1"
>項目</th>
<th
class="title"
:key="n"
>
タイトル-{{n}}
</th>
</template>
</tr>
</thead>
<tbody class="tbody">
<tr
v-for="r of 50"
:key="r"
>
<th class="subtitle">
サブタイトル-{{r}}</th>
<td
v-for="c of 10"
:key="c"
class="cell"
>
セル
</td>
</tr>
</tbody>
</table>
</scroll-sync>
</div>
</template>
<style lang="scss" scoped>
.table-wrap {
border-bottom: 1px solid #777;
border-right: 1px solid #ddd;
width: 800px;
height: 300px;
&::-webkit-scrollbar {
width: 10px;
height: 10px;
}
&::-webkit-scrollbar-track {
background-color: #e4e4e4;
border-radius: 100px;
}
&::-webkit-scrollbar-thumb {
background-color: #d4aa70;
border-radius: 100px;
}
overflow: scroll;
.table {
border-collapse: collapse;
table-layout: fixed;
width: 100%;
th, td {
border: 1px solid #ddd;
padding: 10px 5px;
}
.item {
background: #fff;
width: 200px;
z-index: 10;
}
.title {
width: 160px;
background: cornflowerblue;
color: #fff;
z-index: 8;
}
.subtitle {
width: 200px;
background: #AAA;
color: #fff;
z-index: 5;
}
.cell {
width: 160px;
}
.thead th{
position: sticky;
top: 0;
left: 0;
}
.tbody th{
position: sticky;
left: 0;
}
}
}
</style>
あとはこんな感じで連動することできます。
https://codesandbox.io/s/adoring-water-y9eivz?file=/plugins/vue-scroll-sync.js