之前做移動端的項目一般會選用Mint-ui或者是Vux框架,不得不說這兩款都是非常棒非常好用的UI框架,能給開發工作節省很多時間。
在Mint-ui里關于tabbar的使用,有如下的Demo:
<mt-tabbar v-model="selected">
<mt-tab-item id="訂單">
<img slot="icon" src="http://placehold.it/100x100">
<span slot="label">訂單</span>
</mt-tab-item>
</mt-tabbar>
使用了以后就想...為什么一定要對每個mt-tab-item指定一個id呢?對于tabbar來說,我并不需要關心我按下的對象id是多少,而需要關心的是按下哪個tabbar-item即可。
引申出來這么個問題:
- 那么在父組件中如何區分按下的是哪個子組件呢?
通過判斷children的_uid可以區分出究竟是哪個子組件
- 子組件如何將自身的_uid拋給父組件呢?
調用$parent.$emit('input', _uid),直接這樣調用,會修改v-model綁定value值。
v-model="selected" 可以看成是 v-bind:value="selected" v-on:input="selected = $event.target.value" 的語法糖
有了這幾步分析,然后自己寫了一份簡單的tabbar組件
tabbar.vue
<template>
<div class="l-tabbar">
<slot></slot>
</div>
</template>
<script>
export default {
name: 'LTabbar',
component: 'LTabbar',
props: {
value: {}
},
methods: {
index (id) {
for (let i = 0; i < this.$children.length; ++i) {
if (this.$children[i]._uid === id) {
return i
}
}
return -1
}
}
}
</script>
<style lang="scss">
.l-tabbar {
position: absolute;
width: 100%;
height: auto;
bottom: 0;
left: 0;
right: 0;
background: white;
display: flex;
justify-content: space-around;
}
</style>
tabbarItem.vue
<template>
<div class="tabbar-item"
@click="$parent.$emit('input', id)"
:class="{ 'is-selected': $parent.value === id }">
<div class="item-icon">
<slot name="icon"></slot>
</div>
<div class="item-text">
<slot></slot>
</div>
</div>
</template>
<script>
export default {
name: 'LTabbarItem',
component: 'LTabbarItem',
data () {
return {
id: this.$parent.index(this._uid)
}
}
}
</script>
<style lang="scss">
@import '../../common/style/var.scss';
.tabbar-item {
text-align: center;
margin: 5px auto;
width: 100%;
&.is-selected {
color: $default-color;
}
.item-text {
font-size: 12px;
}
}
</style>
這樣寫完以后,使用的時候會比mint-ui的組件更簡化,可以取消對id的綁定依賴:
<l-tabbar v-model="selected">
<l-tabbar-item v-for="(item, index) in tabItems" :key="index">
<svg slot="icon" :class="icon" aria-hidden="true">
<use :xlink:href="`#${item.icon}`"></use>
</svg>
<span>{{ item.title }}</span>
</l-tabbar-item>
</l-tabbar>
雖然到這一步改造是完成了,但是卻總覺得有些問題。
那么在子組件里面調用父組件的methods是否合適?
但是后來想想tabbar-item僅僅是為tabbar服務的,所以不需要關心太過于耦合,考慮復用性等問題。
如思考的不到位請各位大神能給予一些指導意見。
Github: github.com/lyh2668
AuthBy: lyh2668