uniapp realize different users show different tabbar (bottom navigation bar)

Time:2023-12-15

I. Background

Recently in doing a uniapp development of a small program encountered a demand, I hope that different users logged in to show different tabbar page, but uniapp project pages.json is only a list array, and can not be written as a dynamic effect, in order to achieve this demand, it will be customized tabbar components

II. Effectiveness demonstration

2.1. Role 1: admin account login effect

uniapp realize different users show different tabbar (bottom navigation bar)uniapp realize different users show different tabbar (bottom navigation bar)

2.2, Role 2: tom account login effect

uniapp realize different users show different tabbar (bottom navigation bar)uniapp realize different users show different tabbar (bottom navigation bar)

III. Preliminary work

3.1, the login page as the user enters the small program to display the first page, pages.json file in the pages array of the first set to the login page

3.2. pages.json configure the basic path of the tabbar (just the path)

{
	"pages": [ //The first item in the pages array indicates the application launch page, ref: https://uniapp.dcloud.io/collocation/pages
		{
		    "path" : "pages/login/login",
		    "style" :                                                                                    
		    {
		        "navigationBarTitleText": "",
		        "enablePullDownRefresh": false
		    }
		    
		},
    {
			"path": "pages/index/index",
			"style": {
				"navigationBarTitleText": ""
			}
		}
	    ,{
            "path" : "pages/my/my",
            "style" :                                                                                    
            {
                "navigationBarTitleText": "",
                "enablePullDownRefresh": false
            }
            
        }
        ,{
            "path" : "pages/warn/warn",
            "style" :                                                                                    
            {
                "navigationBarTitleText": "",
                "enablePullDownRefresh": false
            }
            
        }
        
    ],
	"globalStyle": {
		"navigationBarTextStyle": "black",
		"navigationBarTitleText": "uni-app",
		"navigationBarBackgroundColor": "#F8F8F8",
		"backgroundColor": "#F8F8F8"
	},
	"uniIdRouter": {},
  "tabBar": {
    "color": "#999",
    "selectedColor": "#0aa671",
    "borderStyle": "white",
    "list": [
        {
            "pagePath": "pages/index/index"
        },
        {
            "pagePath": "pages/warn/warn"
        },
        {
            "pagePath": "pages/my/my"
        }
    ]
  }
}

IV. Creating the tabbar component

4.1 Step 1: Create a components folder in the project and create the tabbar component under the folder

uniapp realize different users show different tabbar (bottom navigation bar)

The specific code for the tabbar component is as follows:

<template>
    <view class="tab">
         <view v-for="(item,index) in list" :key="index" class="tab-item" @click="switchTab(item, index)">
            <image class="tab_img" :src="currentIndex == index ? item.selectedIconPath : item.iconPath"></image>
            <view class="tab_text" :style="{color: currentIndex == index ? selectedColor : color}">{{item.text}}</view>
        </view>
    </view>
</template>

<script>
    export default {
        props: {
            selectedIndex: { // currently selected tab index
                default: 0
            },
        },
        data() {
            return {
                color: "#666666",
                selectedColor: "#00BAB2",
                list: [],
                currentIndex:0,
            }
        },
        created() {
            this.currentIndex = this.selectedIndex;
            
            let _this = this
            
            if (uni.getStorageSync('identify') == 'tom') {
                //Role 1
                _this.list = [{
                        "pagePath": "/pages/index/index",
                        "iconPath": "/static/tab/home.png",
                        "selectedIconPath": "/static/tab/home_active.png",
                        "text": "Home"
                    },
                    {
                        "pagePath": "/pages/my/my",
                        "iconPath": "/static/tab/my.png",
                        "selectedIconPath": "/static/tab/my_active.png",
                        "text": "My"
                    }
                ]
            } else {
                //Role 2
                _this.list = [{
                        "pagePath": "/pages/index/index",
                        "iconPath": "/static/tab/home.png",
                        "selectedIconPath": "/static/tab/home_active.png",
                        "text": "Home"
                    },
                    {
                       "pagePath": "/pages/warn/warn",
                       "iconPath": "/static/tab/warn.png",
                       "selectedIconPath": "/static/tab/warn_active.png",
                       "text": "Alerts"
                    },
                    {
                        "pagePath": "/pages/my/my",
                        "iconPath": "/static/tab/my.png",
                        "selectedIconPath": "/static/tab/my_active.png",
                        "text": "My"
                    }
                ]
            }
        },
        methods: {
            switchTab(item, index) {
                this.currentIndex = index;
                let url = item.pagePath;
                uni.redirectTo({url:url})
                
            }
        }
    }
</script>

<style lang="scss">
    .tab {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        height: 100rpx;
        background: white;
        display: flex;
        justify-content: center;
        align-items: center;
        padding-bottom: env(safe-area-inset-bottom); // Fits into the bottom of the iphoneX

        .tab-item {
            flex: 1;
            text-align: center;
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            .tab_img {
                width: 60rpx;
                height: 60rpx;
            }
            .tab_text {
                font-size: 30rpx;
                margin-top: 9rpx;
            }
        }
    }
</style>

Note: Jump path: pagePath starts with /.

Description: tab_img can modify the icon size, tab_text can modify the text size

4.2 Step 2: Inmain.jsfile to include the customizedtabBarDefined as a global component

// main.js file
import tabBar from "@/components/tabbar/tabbar.vue"
Vue.component('tabBar',tabBar)

4.3 Step 3: Introduce the tabbar component on the page you need to use.

// e.g. index page
<template>
  <view>
    warning
    <tabBar selectedIndex = 0></tabBar>
  </view>
</template>

//as on the warn page
<template>
  <view>
    warning
    <tabBar selectedIndex = 1></tabBar>
  </view>
</template>


//as my page
<template>
  <view>
    warning
    <tabBar selectedIndex = 2></tabBar>
  </view>
</template>

4.4 Step 4: Hide the navigation bar configured in pages.json, and use the encapsulated tabbar component to configure the tabbar component on the page where it needs to be introduced.

// The same is true for the warn page index and the my page.
<script>
  export default {
    onShow() {
       // Hide the navigation bar configured in pages.json, using the wrapped tabbar component.
      uni.hideTabBar({
        animation:false
     })
    }
  }
</script>

V. Logic for tabbar switching on login page according to different identities

//Login login page
<template>
<view class="container">
<view class="form-group">
<text>Username:</text>
<input v-model="username" type="text" placeholder=" User name" ></input>
</view>

<view class="form-group">
  <view style="margin-left: 30rpx;"></view>
<text>Password:</text>
<input v-model="password" type="password" placeholder=" Password please "></input>
</view>
<view class="btn-login">
< button@click ="login"> Login </button>
</view>
</view>
</template>

<script>
export default {
  data() {
    return {
      //Default account set on the page admin, password 123456
      username: 'admin',
      password: '123456'
    };
  },
  onShow() {
    uni.clearStorageSync('identify')
  },
  methods: {
    login() {
      const username = this.username;
      const password = this.password;
      let identify = '';

      // Identity based on username and password
      if (username === 'tom' && password === '123456') {
        identify = 'tom';
      } else if (username === 'admin' && password === '123456') {
        identify = 'admin';
      } else {
        // Wrong username or password
        console.log('Wrong username or password');;
        return;
      }
      // Local storage
      uni.setStorageSync('identify', identify);

      // Go to home page
      uni.switchTab({
        url: '/pages/index/index'
      });
    }
  }
};
</script>

<style scoped>
.container {
padding: 30rpx;
}

.form-group {
  display: flex;
  align-items: center;
  justify-content: center;
margin-bottom: 30rpx;
}
input{
  border: 1rpx solid #00BAB2;
  padding: 10rpx;
}
button {
background-color: #00BAB2;
color: white;
border: none;
border-radius: 20rpx;
}
</style>

VI. Issues for expansion

6.1, Problem: When it’s character 1, clicking on tabbar my page text and icons cause colors to flicker

6.2 Reason: Role 1 has two tabbars and the index value of the “My” page is 1, while the index value of the “My” page is 1, and the index value of the “My” page is 1.selectedIndex is set to be outside the index range of the role 1 tab. In this case, thecurrentIndex The default value of theselectedIndex Setting it to 2 causes thecurrentIndex does not match the actual tab selected, causing the text and icon display colors to flicker.

6.3. Settlement: in passingselectedIndexto<tabBar> component and ensure that it does not exceed the index range of the role 1 tab

6.4. Re-modify my page

// my page
<template>
  <view>
    my
   <tabBar :selectedIndex="selectedTabIndex"></tabBar>

  </view>
</template>

<script>
  export default {
    computed: {
      //Judge what role
      selectedTabIndex() {
        return uni.getStorageSync('identify') === 'tom' ? 1 : 2;
      }
    },
    onShow() {
      uni.hideTabBar({
        animation:false
     })
    },
   
  }
</script>

PS: Please give a like if it helps you, and feel free to discuss any questions in the comment section.ღ( ´・・ᴗ・` ) ღ( ´・・ᴗ・` )

Recommended Today

Resolved the Java. SQL. SQLNonTransientConnectionException: Could not create connection to the database server abnormal correctly solved

Resolved Java. SQL. SQLNonTransientConnectionException: Could not create connection to the database server abnormal correct solution, kiss measuring effective!!!!!! Article Catalog report an error problemSolutionscureexchanges report an error problem java.sql.SQLNonTransientConnectionException:Could not create connection to database server Solutions The error “java.sql.SQLNonTransientConnectionException:Could not create connection to database server” is usually caused by an inability to connect to the […]