Home > Web Front-end > Uni-app > body text

Teach you step by step how to implement dynamic routing and dynamic tabbar based on the uniapp framework

青灯夜游
Release: 2021-08-27 19:10:32
forward
13588 people have browsed it

How to implement dynamic routing and dynamic tabbar based on the uniapp framework? This article will introduce you to the actual combat of uniapp dynamic routing and teach you step by step how to implement dynamic routing in uniapp.

Teach you step by step how to implement dynamic routing and dynamic tabbar based on the uniapp framework

uniapp is relatively convenient and fast to develop apps. Official website tutorial is very detailed, and you can find answers to almost all questions. There are also many introductory tutorials on the Internet. There are several video tutorials on Tencent Classroom and Bilibili. They seem to be okay (actually I haven’t watched them much). They are more practical and you can try them out.

This article assumes that the reader has basically mastered the introductory development skills of uniapp. If you have not yet mastered uniapp, but you are ready to carry out related development, just start with the official documentation and combine it with the actual video operation. It is recommended above. are all good. Okay, let’s get to the topic of this article - How to implement dynamic routing and dynamic tabbar based on the uniapp framework.

Situation Analysis

## There is a routing plug-in Vue Router on the vue project, and all routes are It is unified management, which can uniformly intercept and control the next action, but on uniapp, the situation is different. There is no routing plug-in on uniapp, and the pages are divided into tabbar and non-tabbar. Page jumps also have their own set of APIs. The most important route interception function is not supported. All pages are configured in advance in the page.json file. good.

Requirements Analysis

Suppose we want to make a set of corresponding functions on the app The thing about user permissions is that different users, according to the permission configuration, determine which pages and buttons they can use after coming in, and even control the tabbar. This requirement requires controlling routing content and guidance based on permissions, but this cannot be achieved under current conditions. However, many people in the plug-in market have written routing plug-ins. The ideas are actually in line with the vue Router on the web side. The only one that can fully meet the needs is this

routing plug-in.

Another very important requirement is the dynamic tabbar. This is a very important content. It is a column of buttons under the homepage after the app is logged in. These tabbars basically include the main content of the app. How to achieve dynamic The tabbar is controlled based on permissions as mentioned above. For example, there can only be five tabbars at most, so how can I control A to see 5 tabbars and B to only see 3? This requirement cannot be realized on the native uniapp. The native one can only configure pages. TabBar is a sub-configuration of pages. However, someone in the plug-in market has implemented the componentization of tabbar, and we can try customized development.

To sum up, there are actually two requirements:

1. Implement uniapp routing guard;

2. Implement dynamic tabbar;

The first requirement , some solutions were mentioned before; the second requirement, dynamic tabbar, needs to be implemented in combination with the

tabbar component of uview component library. Let’s analyze the current framework and plug-in capabilities, and combine the above requirements, we will have this picture:

Teach you step by step how to implement dynamic routing and dynamic tabbar based on the uniapp framework

There are some contents in this picture that were not mentioned before, such as state management. , Local cache, this is a key part that will be used later, and will be mentioned in the design part below.

Program design##Let’s take a look at the business process design:

1. The app enters the user name and password to log in;

2. Intercept in the routing guard to determine whether there is routing information in the local data when the user logs in; if not, go to step 3, if so, go Step 4;

3. Call the interface to obtain the route and obtain the routing data from the server; store the routing data locally (vuex, uniapp cache);

4. Change the tabbar The hierarchical data is separately stored and combined with uview's tabbar component to implement dynamic tabbar;

5. Store a full set of app buttons locally (except for tabbar, other pages are jumped through buttons), and communicate with the server Compare the obtained data to obtain a configuration data set indicating whether the button is displayed or not;

6. After the routing information is initialized, enter the user-customized initial page or home page;

ok, analyze That's almost it. Let's introduce the specific practical steps.

solution

1. Implement route guard#

The routing plug-in recommends uni-simple-router. For specific tutorials, you can refer to its official document, which is written in more detail. The following is my simple practical tutorial.

Install the uni-simple-router plug-in

npm install uni-simple-router
Copy after login

Next, perform modular configuration , create the folder router, the contents of the folder are as follows:

Teach you step by step how to implement dynamic routing and dynamic tabbar based on the uniapp framework

The home file contains the routing configuration for all pages, like this:

const home = [
 {
      path: '/pages/login/login',
      aliasPath:'/app/login',  //对于h5端适用
      name: 'login',
        meta: {
         title: '登录',
     }
    },
 {
      path: '/pages/index/index',
      aliasPath:'/app/index',  //对于h5端适用
      name: 'index',
        meta: {
         title: '首页',
     }
    }]
export default home
Copy after login

Must be required here One more thing, since this plug-in does not have a dynamic writing function, if we want to implement permission management, we must configure complete routing locally; and the content in pages.json must also be fully configured, but the tabbar configuration is somewhat different, which will be discussed later. ;

The index under the modules folder is just a code for module reading;

const files = require.context('.', false, /\.js$/)
const modules = []

files.keys().forEach(key => {
  if (key === './index.js') return
  const item = files(key).default
  modules.push(...item)
})

export default modules
Copy after login

The index content under the router root directory is mainly the routing guard:

import modules from './modules/index.js'
import Vue from 'vue'
import Router from 'uni-simple-router'
import store from '@/store/store.js'

Vue.use(Router)
//初始化
const router = new Router({
 APP: {
  holdTabbar: false //默认true
 },
 h5: {
  vueRouterDev: true, //完全使用vue-router开发 默认 false  
 },
 routes: [...modules] //路由表
});

//全局路由前置守卫
router.beforeEach((to, from, next) => {
 // 首先判断是否存在路由信息
 //不存在就先调用接口得到数据
   //具体内容可以参照上文的方案设计内容
})
// 全局路由后置守卫
router.afterEach((to, from) => {})
export default router;
Copy after login

Finally, The main.js of the app needs to be quoted like this:

import router from './router/index.js'
import { RouterMount } from 'uni-simple-router'
...

//v1.3.5起 H5端 你应该去除原有的app.$mount();使用路由自带的渲染方式
// #ifdef H5
 RouterMount(app,'#app');
// #endif

//为了兼容小程序及app端必须这样写才有效果
// #ifndef H5
 app.$mount(); 
// #endif
Copy after login

As for the subsequent routing usage, please directly read the official documentation, which is more clear, and the usage is similar to vue-router. What needs special explanation here are several configurations of the block initialized by the above code: holdTabbar: false, vueRouterDev: true. The former means that the native tabbar interception is replaced on the app side and intercepted in this plug-in; the latter means that it is completely used in h5 The API of vue-router has abandoned the native API including this plug-in and uniapp. Please use the latter with caution.

2. Combined with state management and uniapp data cache management app cache overhead

Here In fact, it is not difficult, and there is no code given. It is very simple.

I can store the data obtained from the server in the state management, but the vuex data is stored in the memory and is easily lost. For example, if I use the app for a while, I pull it to the background, and if I click it again immediately, it can be used. However, if the time is too long, the cache is accidentally cleared, or the timeout limit of the server is exceeded, then I click the app again. , some data may be missing. This problem needs to be handled by the route guard. When the route jumps, it will be judged whether the relevant status data exists, and if it does not exist, it will be processed again.

Let me introduce the data caching API of uniapp, which is more stable, especially on the app. It is not a cache concept, but exists persistently, unless you call its clearing method. You can use these two to store some data separately and do some control together. You can figure out the specific implementation yourself. For example, if you pull it back from the background and the status management data is gone, but the time is still within the server timeout range, then the token data that has not timed out will be stored in uniapp's data cache. I will check the relevant permissions based on this token. Route information, assign a value to vuex, and then perform subsequent operations; if it times out after pulling it back, it will return directly to the login page. In this area, I just provide ideas, and they are successful ideas. I have personally tested them to be effective.

3. Implement dynamic tabbar

Okay, we can get to this point, The long march of thousands of miles is only half done. Don't look at the following content, it actually took me more time to put together the relevant information than the above.

Since tabbar is configured separately, native uniapp has no dynamic configuration method. After searching around, I found that uview's tabbar component can be implemented. Let’s list the steps here: step by step, it can be achieved!

1. Modify the pages.json configuration

"tabBar": {
  "list": [{
   "pagePath": "pages/index/index"
  },{
   "pagePath": "pages/about/about"
  }]
 },
Copy after login

Like this, leave only these The content is much less than the native configuration.

#2. Store the tabbar information separately in a global object

This step It can be stored in vuex because it is easy to read. Uniapp's data cache is a little more troublesome to read. Put it in vuex, it is very convenient to retrieve, like this:

this.$store.state.userInfo.tabbarlist
Copy after login

3. Configure the tabbar component on each tabbar page

Copy after login

The format of the template part should be as above, with the tabbar and the text content juxtaposed; the jump code is as follows, both methods are possible, see documentation## for details #

changeTb(index) {
    // uni.switchTab({
    //  url: this.$store.state.userInfo.tabbarlist[index].pagePath
    // });
    this.$Router.pushTab(this.$store.state.userInfo.tabbarlist[index].pagePath)
   }
Copy after login

It should be noted that this method hides the native tabbar of uniapp; the tabbarlist data in the state management used above is a tabbar configuration with complete structural parameters, but the tabbar page may not be complete. , determined by user permissions.

Okay, this article has clearly explained the complete solution of dynamic routing and dynamic tabbar. You can follow my ideas and gradually improve the details according to your own needs. I hope it will be inspiring and useful to you. help. If it is useful to you, please click to share, thank you!

Recommended: "uniapp tutorial"

The above is the detailed content of Teach you step by step how to implement dynamic routing and dynamic tabbar based on the uniapp framework. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!