在 mint-ui 中,picker 是很常用也比較復(fù)雜的一個組件,讓我們拆解這個組件看看它是如何實現(xiàn)的。
整體結(jié)構(gòu)
來看看 picker 的整體結(jié)構(gòu):
picker.vue
<div class="picker" :class="{ 'picker-3d': rotateEffect }">
<!-- 頂部工具欄區(qū)域 -->
<div class="picker-toolbar" v-if="showToolbar"><slot></slot></div>
<div class="picker-items">
<!-- picker 列 -->
<picker-slot v-for="slot in slots"></picker-slot>
<!-- 標識選中區(qū)域 -->
<div class="picker-center-highlight" :style="{ height: itemHeight + 'px', marginTop: -itemHeight / 2 + 'px' }"></div>
</div>
</div>
從代碼中可以發(fā)現(xiàn)單個滾動組件其實是 picker-slot 組件,而 picker 只是做了個外部容器并且提供了各種 set 和 get 方法用來操作組件和獲取數(shù)據(jù)。下面是 picker 提供的方法
picker 中的方法
method: {
slotValueChange () {}, // 觸發(fā) picker 的 change 事件
getSlot (slotIndex) {}, // 過去某一列 slot
getSlotValue (index) {}, // 獲取某一列 slot 的當前值
setSlotValue (index, value) {}, // 設(shè)置某一列 slot 的當前值
getSlotValues (index) {}, // 獲取 slot 的 values
setSlotValues (index, values) {}, // 設(shè)置 slot 的 values
getValues () {}, // 獲取多個組件合成的值
setValues (values) {} // 同時設(shè)置多列 slot 的值
}
然后看下 picker-slot 組件的整體結(jié)構(gòu)~
picker-slot.vue
<div class="picker-slot" :class="classNames" :style="flexStyle">
<div v-if="!divider" ref="wrapper" class="picker-slot-wrapper" :class="{ dragging: dragging }" :style="{ height: contentHeight + 'px' }">
<div class="picker-item" v-for="itemValue in mutatingValues" :key="itemValue" :class="{ 'picker-selected': itemValue === currentValue }" :style="{ height: itemHeight + 'px', lineHeight: itemHeight + 'px' }">
{{ typeof itemValue === 'object' && itemValue[valueKey] ? itemValue[valueKey] : itemValue }}
</div>
</div>
<div v-if="divider">{{ content }}</div>
</div>
從 HTML 源碼中可以看出:這里使用了 divider
屬性來決定顯示內(nèi)容還是分隔符。如果 divider=true
那么直接顯示 <div v-if="divider">{{ content }}</div>
分隔符元素,否則顯示 picker 選項列表。
而 picker 選項列表其實就是使用 v-for 遍歷渲染的一組元素列表,通過 CSS 的 translate 屬性偏移元素以達到移動選擇器的功能。可以從 dom 結(jié)構(gòu)中找到具體的樣式~
所以,小結(jié)下:picker 只是容器,而 picker-slot 顯示了單列選項列表,并通過 translate 偏移實現(xiàn)選中效果。一個 picker 是由一個或多個 picker-slot 組件組成。
事件監(jiān)聽
picker 組件中只有一個 change 監(jiān)聽事件。看下代碼~
picker.vue
methods: {
slotValueChange () {
this.$emit('change', this, this.values)
},
...
}
從代碼中可以看到 picker 的 change 事件傳遞的值是 this 和 this.values,所以在定義 change 監(jiān)聽事件方法的時候可以獲取到到 picker 組件實例本身,通過實例可以使用 picker 實例中的所有方法。
onYearChange(picker, values) {
picker.setSlotValues(1, address[values[0]]);
},
在 picker 文檔中也有說到這個:
change 事件
在 change 事件中,可以使用注冊到 picker 實例上的一些方法:
- getSlotValue(index):獲取給定 slot 目前被選中的值
- setSlotValue(index, value):設(shè)定給定 slot 被選中的值,該值必須>* 存在于該 slot 的備選值數(shù)組中
- getSlotValues(index):獲取給定 slot 的備選值數(shù)組
- setSlotValues(index, values):設(shè)定給定 slot 的備選值數(shù)組
- getValues():獲取所有 slot 目前被選中的值(分隔符 slot 除外)
- setValues(values):設(shè)定所有 slot 被選中的值(分隔符 slot 除外),該值必須存在于對應(yīng) slot 的備選值數(shù)組中
來看看 change 事件的觸發(fā)時機,觸發(fā)條件是組件 create 之后或者 picker-slot 組件的值有變化時。
在 created 時觸發(fā)的很好理解,直接執(zhí)行 slotValueChange 方法。而接收 picker-slot 組件的值發(fā)生變化用到了 src/mixins/emittier.js
這個文件中的方法。方法有兩個,分別是向父級組件傳輸數(shù)據(jù)的 dispatch 方法和向子級組件廣播數(shù)據(jù)的 broadcast 方法。這里由于是子組件往父組件發(fā)送消息所以是 dispatch 方法~
picker.vue
created () {
this.$on('slotValueChange', this.slotValueChange)
this.slotValueChange()
},
picker-slot.vue
watch: {
currentValue (val) {
this.doOnValueChange()
if (this.rotateEffect) {
this.planUpdateRotate()
}
this.$emit('input', val)
this.dispatch('picker', 'slotValueChange', this)
}
}
當某個 picker-slot 組件的當前值有所變化就會向 picker 派發(fā)消息,picker 收到消息后觸發(fā) change 事件。
dispatch 方法
dispatch (componentName, eventName, params) {
var parent = this.$parent
var name = parent.$options.componentName
while (parent && (!name || name !== componentName)) {
parent = parent.$parent
if (parent) {
name = parent.$options.componentName
}
}
if (parent) {
parent.$emit.apply(parent, [eventName].concat(params))
}
},
picker-slot 組件的滑動效果實現(xiàn)
基本原理:
- 使用了
transform: translate3d(0, 0, 0) rotateX(0);
來做選項列表的偏移。 - 為選中項添加了
.picker-selected
這個 class 來實現(xiàn)選中項的效果。 - 通過單個選項的高度、選中值的索引、顯示選項的數(shù)量、選項總數(shù)這些屬性來計算 translate 偏移值。
- 如果支持 touch 則使用
touchstart
、touchmove
、touchend
和touchcancel
方法監(jiān)聽手勢,否則使用mousedown
、mousemove
和mouseup
方法監(jiān)聽鼠標行為。
下面是 picker-slot 的具體滾動邏輯:
- 導(dǎo)入了 draggable.js 文件,這個文件定義了一個拖動元素的方法
draggable(element, options)
,其中 element 是 dom 元素,而 options 對象中有三個方法:start()
、drag()
和end()
方法分別對應(yīng)開始拖拽、拖拽中和結(jié)束拖拽。 - 在渲染完成后執(zhí)行了 initEvent() 方法,改方法調(diào)用 draggable.js 中的方法。
mounted () {
this.ready = true
if (!this.divider) {
this.initEvents()
this.doOnValueChange()
}
if (this.rotateEffect) {
this.doOnValuesChange()
}
},
initEvents () {
var el = this.$refs.wrapper
var dragState = {}
var velocityTranslate, prevTranslate, pickerItems
draggable(el, { ... })
}
- 選取
this.$ref.wrapper
這個元素(即包裹選項列表的 div 元素),使用 draggable 方法定義拖拽各階段的行為。 - 在 start 方法中記錄了開始拖拽時的狀態(tài) dragState,取消了正在進行的動畫,并記錄所有選項元素。
start: (event) => {
cancelAnimationFrame(this.animationFrameId)
this.animationFrameId = null
dragState = {
range: this.dragRange,
start: new Date(),
startLeft: event.pageX,
startTop: event.pageY,
startTranslateTop: translateUtil.getElementTranslate(el).top
}
pickerItems = el.querySelectorAll('.picker-item')
},
- 在 drag 方法中不斷更新拖拽狀態(tài) dragState,通過計算元素的偏移量,通過偏移量 translate 改變 transform:translate() 的偏移位置實現(xiàn)元素列表隨手指(鼠標)移動的效果,全局記錄這個偏移量,最后如果有滾動效果需要更新滾動效果動畫和樣式。
drag: (event) => {
this.dragging = true
dragState.left = event.pageX
dragState.top = event.pageY
var deltaY = dragState.top - dragState.startTop
var translate = dragState.startTranslateTop + deltaY
// 移動整個元素
translateUtil.translateElement(el, null, translate)
velocityTranslate = translate - prevTranslate || translate
prevTranslate = translate
if (this.rotateEffect) {
this.updateRotate(prevTranslate, pickerItems)
}
},
- 在 end 方法中通過拖拽狀態(tài) dragState 計算拖拽的時間和拖拽的距離;當記錄很小時計算下是否需要移動選項元素;當拖拽時間小于 300 毫秒,計算一個快速拖拽的位移;當 dom 加載完成后計算最后的 translate 偏移量,其中拖拽和快速拖拽的偏移量是不同的;最后,將改變 $el 元素的偏移量實現(xiàn)滾動效果。并且通過偏移量獲取當前對應(yīng)的選項值。如果有滾動效果,還需要進行滾動動畫的更新。
end: (event) => {
this.dragging = false
var momentumRatio = 7
var currentTranslate = translateUtil.getElementTranslate(el).top
var duration = new Date() - dragState.start
let distance = Math.abs(dragState.startTranslateTop - currentTranslate)
var itemHeight = this.itemHeight
var visibleItemCount = this.visibleItemCount
let rect, offset
if (distance < 6) {
rect = this.$el.getBoundingClientRect()
offset = Math.floor((event.clientY - (rect.top + (visibleItemCount - 1) * itemHeight / 2)) / itemHeight) * itemHeight
if (offset > this.maxTranslateY) {
offset = this.maxTranslateY
}
velocityTranslate = 0
currentTranslate -= offset
}
var momentumTranslate
if (duration < 300) {
momentumTranslate = currentTranslate + velocityTranslate * momentumRatio
}
var dragRange = dragState.range
this.$nextTick(() => {
var translate
if (momentumTranslate) {
translate = Math.round(momentumTranslate / itemHeight) * itemHeight
} else {
translate = Math.round(currentTranslate / itemHeight) * itemHeight
}
// translate must in the range
translate = Math.max(Math.min(translate, dragRange[1]), dragRange[0])
// translate element
translateUtil.translateElement(el, null, translate)
// get current value by translate
this.currentValue = this.translate2Value(translate)
if (this.rotateEffect) {
this.planUpdateRotate()
}
})
// clear dragState
dragState = {}
}
隱藏屬性 —— 滾動效果
在 picker 中有一個 rotateEffect 屬性在文檔中沒有提及,它的作用是讓選擇器有圓形滾動效果,如下:
<mt-picker :slots="yearSlot" @change="onYearChange" :visible-item-count="3" rotate-effect></mt-picker>
這是使用的
transform:totateX(45deg)
讓元素有一個角度來實現(xiàn)滾動效果。
最后
picker 的源碼在此
關(guān)于 picker 組件的分析就到這里啦,如果對于 picker 還有任何疑問,可以在評論區(qū)留言,共同學(xué)習(xí)。