一、uniapp中tabbar和tab组件的区别
uniapp中提供了两个tab切换组件:tabbar和tab组件,两者虽然都能实现tab切换的功能,但是它们却有很大的区别: 首先,tabbar是一个全局组件,一旦在app.vue中使用,它就会在每个子页面上显示,而tab组件是在某个页面内使用的,一旦离开该页面,tab组件就无法使用了。 其次,tabbar与原生APP的底部导航栏非常相似,能够实现同时切换页面和样式的效果,而tab组件只是改变了当前页面的显示内容,无法对应的改变样式
<!-- tabbar组件示例 -->
<template>
<view class="container">
<tabbar>
<tabbar-item icon="home" text="主页" url="/pages/home/home"></tabbar-item>
<tabbar-item icon="contact" text="联系人" url="/pages/contact/contact"></tabbar-item>
<tabbar-item icon="setting" text="设置" url="/pages/setting/setting"></tabbar-item>
</tabbar>
<router-view></router-view>
</view>
</template>
<!-- tab组件示例 -->
<template>
<view>
<view class="tabBar">
<text class="item" :class="{active:index===0}" @click="changeTab(0)">选项一</text>
<text class="item" :class="{active:index===1}" @click="changeTab(1)">选项二</text>
</view>
<view v-show="index===0">选项一的内容</view>
<view v-show="index===1">选项二的内容</view>
</view>
</template>
二、tabbar组件的使用
在uniapp中使用tabbar组件非常方便,只需在app.vue中定义tabbar和tabbar-item即可,如下图所示:
<template>
<view class="container">
<tabbar>
<tabbar-item icon="home" text="主页" url="/pages/home/home"></tabbar-item>
<tabbar-item icon="contact" text="联系人" url="/pages/contact/contact"></tabbar-item>
<tabbar-item icon="setting" text="设置" url="/pages/setting/setting"></tabbar-item>
</tabbar>
<router-view></router-view>
</view>
</template>
<script>
import tabbar from '@/components/tabbar.vue'
import tabbar-item from '@/components/tabbar-item.vue'
export default {
components: {
tabbar,
'tabbar-item': tabbar-item
}
}
</script>
在tabbar-item中配置对应的图标、文本和路径即可实现页面的切换效果。此外,我们还可以在tabbar中设置默认选中的tab:
<template>
<view class="container">
<tabbar :selected="0">
<tabbar-item icon="home" text="主页" url="/pages/home/home"></tabbar-item>
<tabbar-item icon="contact" text="联系人" url="/pages/contact/contact"></tabbar-item>
<tabbar-item icon="setting" text="设置" url="/pages/setting/setting"></tabbar-item>
</tabbar>
<router-view></router-view>
</view>
</template>
三、tab组件的使用
tab组件相对于tabbar,更加灵活,可以自由定义样式和内容。我们只需在页面中定义tab组件和对应的内容区域即可,如下图所示:
<template>
<view>
<view class="tabBar">
<text class="item" :class="{active:index===0}" @click="changeTab(0)">选项一</text>
<text class="item" :class="{active:index===1}" @click="changeTab(1)">选项二</text>
</view>
<view v-show="index===0">选项一的内容</view>
<view v-show="index===1">选项二的内容</view>
</view>
</template>
<script>
export default {
data() {
return {
index: 0
}
},
methods: {
changeTab(index) {
this.index = index
}
}
}
</script>
通过绑定index属性,我们可以实现当前显示哪个tab内容的功能。
四、总结
tab切换是APP开发最常见的功能之一,uniapp中提供了多种形式的tab组件供我们使用。对于简单的页面而言,使用tabbar组件非常方便快捷,可以快速实现底部导航栏的效果。对于比较复杂的页面,我们可以使用tab组件自由定义样式和内容。 总之,uniapp提供了非常便捷的tab切换组件,开发者可以根据自己的需要来选择使用哪种方式。希望本文能够对大家有所帮助。