业务需求如下图:顶部是一个可滑动导航栏,点击导航栏之后,下面的部分局部刷新。
1、定义top-nav组件
<template>
<view class="">
<view class="scroll-box">
<scroll-view class="scroll-view_H" scroll-x="true">
<view class="scroll-view-item_H" :class="currentItem.name==tab.name ? 'uni-tab-active' : ''" v-for="tab in topNavList" :key="tab.name" @tap="tapNav(tab)">
<view class="uni-tab-item-title" :class="currentItem.name==tab.name ? 'uni-tab-item-title-active' : ''">{{tab.name}}</view>
</view>
</scroll-view>
</view>
<view class="" style="height: 100rpx;">
<!-- 因为顶部导航栏需要固定定位,留取同样高度的盒子占位保证布局 -->
</view>
<view>
<!-- 被选中的导航栏对应的内容在这里渲染 -->
<slot></slot>
</view>
</view>
</template>
<script>
export default {
name: 'top-nav',
props: {
topNavList: {
type: Array
}
},
data() {
return {
currentItem: {
name:'全局概览'
},
}
},
created() {
},
methods: {
tapNav(item) {
this.currentItem = item
this.$emit("currentCode",item.code)
}
}
}
</script>
<style>
.scroll-box{
position: fixed;
left: 0;
right: 0;
top: 0;
}
.scroll-view_H {
white-space: nowrap;
width: 100%;
display: flex;
justify-content: space-between;
}
.scroll-view-item_H {
flex: 1;
display: inline-block;
height: 60rpx;
line-height: 60rpx;
text-align: center;
margin: 10rpx;
padding-left: 20rpx;
padding-right: 20rpx;
}
.uni-tab-active{
background-color: #C0C0C0;
border-radius: 30rpx;
}
.uni-tab-item-title-active {
color: #007AFF;
}
</style>
2、引用组件
通过 Vue 的 component 元素加一个特殊的 is attribute 来实现在不同组件之间进行动态切换
<template>
<view class="content-box">
<top-nav :topNavList="topNavList" @currentCode = "currentCode">
<component :is="currentComponentName"></component>
</top-nav>
</view>
</template>
<script>
import TopNav from '@/components/top-nav/top-nav.vue'
import globalOverview from '@/pages/statisticalReports/components/globalOverview.vue'
import equipmentDetails from '@/pages/statisticalReports/components/equipmentDetails.vue'
import wageStatistics from '@/pages/statisticalReports/components/wageStatistics.vue'
export default{
components:{
TopNav,
globalOverview,
equipmentDetails,
wageStatistics
},
data(){
return{
currentComponentName:'globalOverview',
topNavList:[{
name:'全局概览',
code:'globalOverview'
},{
name:'设备详情',
code:'equipmentDetails'
},{
name:'工资统计',
code:'wageStatistics'
}]
}
},
methods:{
currentCode(code){
this.currentComponentName = code;
}
}
}
</script>
<style>
</style>
3、拓展:如果想要保存失活组件的状态,可以用keep-alive包裹
<!-- 失活的组件将会被缓存!-->
<keep-alive>
<component v-bind:is="currentTabComponent"></component>
</keep-alive>