vue的TabBar组件 Posted on 2021-04-18 | In vue vue的TabBar组件 TabBar组件的功能123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384<template> <div class="tool-bar"> <!-- tab 按钮,需要一个数据源,通过数据源去驱动视图 --> <div class="tool-bar-item" v-for="(item, index) in toolBarData" :key="index" @click="onChangeFragment(item, index)"> <img class="tool-bar-item-img" :src="[index === selectIndex ? item.hIcon : item.nIcon]" alt=""> <p class="tool-bar-item-name" :class="{'tool-bar-item-name-h' : index === selectIndex}">{{item.name}}</p> </div> </div></template><script>/** * ToolBar的功能: * 1.永远位于页面的最底部 * 2.点击 toolbar 按钮的时候,页面发生对应的切换 * 3.按钮分 默认 和 选择 两个状态 * * 能力和约束 * 1.不具备的能力(回调) * 2.通过一个回调,告诉父组建,按钮点击的事件 * 3.当按钮被选中的时候,应该切换按钮的状态*/export default { data: function () { return { toolBarData: [ { nIcon: require('@img/xx.svg'), hIcon: require('@img/xx.svg'), name: 'xx', componentName: 'home' }, { nIcon: require('@img/xx.svg'), hIcon: require('@img/xx.svg'), name: 'xx', componentName: 'my' } ], selectIndex: 0, // 选中的tab按钮 isIphoneX: window.isIphoneX } }, methods: { onChangeFragment (item, index) { this.selectIndex = index this.$emit('onChangeFragment', item.componentName) } }}</script><style lang="scss" scoped>@import '@css/style.scss';.tool-bar { width: 100%; height: 46px; display: flex; justify-content: space-around; background-color: white; box-shadow: 0 0 16px 0 rgba(0,0,0,0.2); border-top: 1px solid $lineColor; font-size: 16px; &-item { text-align: center; padding: px2rem(4) 12px; display: flex; flex-direction: column; justify-content: center; align-items: center; &-img { width: px2rem(22); height: px2rem(22); } &-name { font-size: $minInfoSize; margin-top: px2rem(4); &-h { color: $mainColor; } } }}</style> 12345678910111213141516171819202122232425262728293031323334353637383940414243Main.vue <template> <div class="main"> <!-- 失活的组件将会被缓存! --> <keep-alive> <component :is="currentComponent"></component> </keep-alive> <ToolBar @onChangeFragment="onChangeFragment" /> </div></template><script>import ToolBar from '@c/ToolBar'export default { data () { return { currentComponent: 'home' } }, components: { ToolBar, // 异步组件引入方式,异步组件:只有在需要展示这个组件的时候,才会把组件进行渲染 home: () => import('@c/Home'), shopping: () => import('@c/Shopping'), my: () => import('@c/My') }, methods: { onChangeFragment (componentName) { this.currentComponent = componentName } }}</script><style lang="scss" scoped>.main { width: 100%; height: 100%; display: flex; flex-direction: column;}</style> 12345678910111213141516<template> <div class="home">Home</div></template><script>export default {}</script><style lang="scss" scoped>.home { width: 100%; height: 100%;}</style>