本文分享一個可觸控滑動的 Vue 頁籤元件用法,並附上完整原始碼,方便直接取用與改寫。
<template>
<tab :options="tabOpt" :state.sync="stateIndex"></tab>
</template>
<script type="text/babel">
import tab from 'components/tab_touch';
export default {
data(){
tabOpt:undefined,
stateIndex:0
},
components:{ "tab":tab },
ready(){
this.tabOpt={
count: 2.3,
pin:true,
htmls:[
"<span>白日登山</span>", "<span>望烽火</span>",
"<span>黃昏飲馬</span>", "<span>傍交河</span>",
"<span>行人刁斗</span>", "<span>風沙暗</span>",
"<span>公主琵琶</span>", "<span>幽怨多</span>",
"<span>野營萬裡</span>", "<span>無城郭</span>",
"<span>雨雪紛紛</span>", "<span>連大漠</span>"
],
slideCallback:function (dex) {
console.log(dex);
},
tabClassName:"tab",
tabActiveClassName: "active"
}
}
}
</script>

幾個值得注意的參數:count 控制一畫面顯示幾個頁籤(可帶小數,如 2.3 表示露出下一個的一小部分,暗示可以再滑);pin 決定頁籤列是否吸附在頁面頂端;htmls 是頁籤內容陣列;slideCallback 在滑動落位後回報目前索引;兩個 className 則分別對應一般與選中狀態的樣式類別。
tab.vue
<template>
<div class="fixWrap">
<div class="component-tabsWrap" :id="tabsWrapID" v-touch:pan="onPan">
<div class="component-tabs" :style="wrapStyle">
<div class="component-tab" v-for="item in options.htmls" track-by="$index"
:style="'width:'+tWidth+'px'" @click.stop="this.state=$index"
:class="[options.tabClassName,$index==state?options.tabActiveClassName:'']">
{{{item}}}
</div>
</div>
</div>
</div>
</template>
<style lang="sass" rel="stylesheet/sass">
@import "tab.sass"
</style>
<script lang="babel" type="text/babel">
var VueTouch = require ('vue-touch');
Vue.use (VueTouch);
import requestAnimFrame from "utils/requestAnimFrame"
const sign = (num)=> { return num >= 0 ? 1 : -1 }
export default {
props: ["options", "state"],
data(){
return {
tabsWrapID: undefined, // 外容器 ID
wrapWidth: "", // 外容器寬度
tWidth: 0, // 每一個選項卡應該有多寬
width: 0, // 寬度
startTransX: 0,
transX: 0, // 元素樣式偏移
cssX: 0 // 動作中 css 實際完成的偏移
}
},
methods: {
init(){
this.wrapWidth = document.getElementById (this.tabsWrapID).offsetWidth;
this.tWidth = this.wrapWidth / this.options.count;
this.width = this.tWidth * this.options.htmls.length;
setTimeout(function(){
this.$el.style["height"]= this.$el.children[0].clientHeight+"px";
}.bind(this),0)
if (this.options.pin) {
var elemRect = this.$el.getBoundingClientRect ();
var windowOffset = this.getWindowOffset ();
var winOffsetY = windowOffset.offsetY;
this.elemOffsetY = elemRect.top + winOffsetY;
document.addEventListener ('scroll', this.isTop);
}
},
onPan(event){
if (this.options.disPan) return;
this.transX = event.deltaX + this.startTransX;
this.cssX = this.transX;
if (event.eventType == 4) {
this.transX = -Math.round (-this.transX / this.tWidth) * this.tWidth; // 整格滑動
var start = null;
if (this.transX > 0) {
// 頭部回彈
this.transX = 0;
var speed = 24;
requestAnimFrame (step.bind (this));
function step (timestamp) {
this.cssX -= speed;
if (this.cssX > this.transX) requestAnimFrame (step.bind (this));
else this.startTransX = this.cssX = this.transX;
};
} else if (this.transX < this.wrapWidth - this.width) {
// 尾部回彈
this.transX = this.wrapWidth - this.width;
var speed = 24;
requestAnimFrame (step.bind (this));
function step (timestamp) {
this.cssX += speed;
if (this.cssX < this.transX) requestAnimFrame (step.bind (this));
else this.startTransX = this.cssX = this.transX;
};
} else {
// 整格落位
let speed = 6;
let _sign = sign (this.cssX - this.transX);
if (_sign * (this.cssX - this.transX) > 1) requestAnimFrame (step.bind (this));
else this.cssX = this.transX;
function step (timestamp) {
if (start === null) start = timestamp;
let progress = timestamp - start;
if (progress < 3000) speed *= 1 - progress / 3000;
this.cssX -= _sign * speed;
if (_sign * (this.cssX - this.transX) > 1) requestAnimFrame (step.bind (this));
else this.cssX = this.transX;
};
}
this.startTransX = this.transX; // 滑動結束設置下次滑動起始值
}
},
slideTo(dex){
this.state = dex;
let speed = 10;
// 開頭幾個
if (dex + 1 <= this.options.count) {
this.transX = 0; // 設置應到位置
if (this.startTransX < this.transX) {
let _sign = sign (this.transX - this.startTransX);
this.cssX = this.transX - _sign * this.tWidth;
requestAnimFrame (step.bind (this));
function step () {
this.cssX += _sign * speed;
if (_sign * (this.cssX - this.transX) < 0) requestAnimFrame (step.bind (this));
else {
this.cssX = this.startTransX = this.transX;
if (this.options.slideCallback) this.options.slideCallback (dex);
};
};
}
// 無需動畫
else {
this.cssX = this.startTransX = this.transX;
if (this.options.slideCallback) this.options.slideCallback (dex);
}
}
// 結尾幾個
else if (this.options.htmls.length - dex <= this.options.count) {
this.transX = this.wrapWidth - this.width; // 設置應到位置
if (this.startTransX > this.transX) {
let _sign = sign (this.transX - this.startTransX);
this.cssX = this.transX - _sign * this.tWidth;
requestAnimFrame (step.bind (this));
function step () {
this.cssX += _sign * speed;
if (_sign * (this.cssX - this.transX) < 0) requestAnimFrame (step.bind (this));
else {
this.cssX = this.startTransX = this.transX;
if (typeof this.options.slideCallback == "function") this.options.slideCallback (dex);
}
};
}
else {
this.cssX = this.startTransX = this.transX;
// 無需動畫
if (typeof this.options.slideCallback == "function") this.options.slideCallback (dex);
}
}
// 中間
else {
this.transX = -this.tWidth * dex; // 設置應到位置
let _sign = sign (this.transX - this.startTransX);
if (this.tWidth * (dex + 0.5 * (1 - _sign)) + this.startTransX >= 0 &&
this.tWidth * (dex + 0.5 * (1 - _sign)) + this.startTransX <= this.wrapWidth) {
// 無需動畫
this.cssX = this.transX = this.startTransX;
if (typeof this.options.slideCallback == "function") this.options.slideCallback (dex);
} else {
// 需要動畫
this.cssX = this.transX - _sign * this.tWidth;
requestAnimFrame (step.bind (this));
function step () {
this.cssX += _sign * speed;
if (_sign * (this.cssX - this.transX) < 0) requestAnimFrame (step.bind (this));
else {
this.cssX = this.startTransX = this.transX;
if (typeof this.options.slideCallback == "function") this.options.slideCallback (dex);
}
};
}
}
},
isTop(){
var windowOffset = this.getWindowOffset (),
winOffsetY = windowOffset.offsetY,
isTop;
isTop = this.elemOffsetY <= winOffsetY;
if (isTop) {
this.$el.children[0].style['position'] = 'fixed';
this.$el.children[0].style['top'] = '0';
this.$el.children[0].style['left'] = '0';
} else {
this.$el.children[0].style['position']='relative';
}
return isTop;
},
getWindowOffset(){
var t;
var win = window;
var pageXOffset = (typeof win.pageXOffset == 'number') ? win.pageXOffset :
(((t = doc.documentElement) || (t = body.parentNode)) && typeof t.ScrollLeft == 'number'
? t : body).ScrollLeft;
var pageYOffset = (typeof win.pageYOffset == 'number') ? win.pageYOffset :
(((t = doc.documentElement) || (t = body.parentNode)) && typeof t.ScrollTop == 'number'
? t : body).ScrollTop;
return { offsetX: pageXOffset, offsetY: pageYOffset };
},
},
watch: {
options(){
this.tabsWrapID = parseInt (Math.random () * 1e10);
setTimeout (this.init.bind (this), 10);
},
state(val){
this.slideTo(val)
}
},
computed: {
wrapStyle(){
var _str = "";
if (this.width) _str += `width:${this.width}px;`; // 寬度
_str += `-webkit-transform:translateX(${this.cssX}px);`; // 位移
_str += `transform:translateX(${this.cssX}px);`; // 位移
return _str
}
}
}
</script>
<style lang="sass" rel="stylesheet/sass" type="sass">
.fixWrap
z-index: 999
position: relative
.component-tabsWrap
width: 100%
overflow: hidden
min-height: .1rem
position: relative
background: #fff
.component-tabs
height: 100%
display: table
.component-tab
display: table-cell
box-sizing: border-box
text-align: center
vertical-align: middle
</style>
用 transform 而非 left 做位移:動畫全靠 translateX 走 GPU 合成,避免觸發重排,滑起來才順。頭尾回彈:拖過頭時先夾到邊界值,再用 requestAnimFrame 逐格補間回位。落位減速:中間段落讓速度隨時間線性衰減,模擬摩擦力。pin 吸附:在 scroll 事件中比對元素在文件中的偏移與目前捲動量,跨過臨界點就切換成 fixed。這些都是手寫觸控元件時會反覆用到的模式。