Home Web Front-end uni-app How does uniapp implement preloading of several other TabBar pages?

How does uniapp implement preloading of several other TabBar pages?

Apr 20, 2023 pm 03:08 PM

In recent years, mobile applications have become an essential part of people's lives. With the development of mobile applications, more and more applications adopt TabBar design, especially in apps, TabBar has become the main navigation method for many applications. Among them, the Uniapp framework can be said to be the most popular lightweight cross-platform development framework at present. However, many developers will encounter a common problem when using Uniapp to develop TabBar applications: How to preload several other TabBar pages?

During the Uniapp development process, TabBar can be created by configuring the page in pages.json. For example, define the following pages in pages.json:

{
  "pages": [
    {
      "path": "pages/index/index",
      "style": {}
    },
    {
      "path": "pages/category/category",
      "style": {}
    },
    {
      "path": "pages/cart/cart",
      "style": {}
    },
    {
      "path": "pages/me/me",
      "style": {}
    }
  ],
  "tabBar": {
    "color": "#999999",
    "selectedColor": "#000000",
    "backgroundColor": "#ffffff",
    "borderStyle": "black",
    "list": [
      {
        "pagePath": "pages/index/index",
        "text": "首页",
        "iconPath": "static/tabbar/home.png",
        "selectedIconPath": "static/tabbar/home_active.png"
      },
      {
        "pagePath": "pages/category/category",
        "text": "分类",
        "iconPath": "static/tabbar/category.png",
        "selectedIconPath": "static/tabbar/category_active.png"
      },
      {
        "pagePath": "pages/cart/cart",
        "text": "购物车",
        "iconPath": "static/tabbar/cart.png",
        "selectedIconPath": "static/tabbar/cart_active.png"
      },
      {
        "pagePath": "pages/me/me",
        "text": "我的",
        "iconPath": "static/tabbar/me.png",
        "selectedIconPath": "static/tabbar/me_active.png"
      }
    ]
  }
}
Copy after login

In this configuration file, we define 4 pages and create a TabBar. Among them, each page corresponds to a menu item in the TabBar. When we click on different menu items, Uniapp will jump to the corresponding page.

However, in this process, Uniapp will only preload the current page when it is loaded, and will not preload other pages. Therefore, when we switch from one TabBar page to another, the page may load slowly, affecting the user experience. So, how to solve this problem?

Methods to preload other TabBar pages:

In Uniapp, we can preload other TabBar pages by using uni.request. This method can obtain the data of the specified page by sending a GET request and cache the data. When we click the corresponding TabBar menu item, the system will first check whether the data exists in the cache. If it exists in the cache, it will display the data directly. If it does not exist, it will send the request again and cache the data.

In pages.json, add a preload field to define the page URL that needs to be preloaded:

{
  "pages": [
    {
      "path": "pages/index/index",
      "style": {}
    },
    {
      "path": "pages/category/category",
      "style": {},
      "preload": true
    },
    {
      "path": "pages/cart/cart",
      "style": {},
      "preload": true
    },
    {
      "path": "pages/me/me",
      "style": {},
      "preload": true
    }
  ],
  "tabBar": {
    ...
  }
}
Copy after login

In the above configuration file, we add new fields for category, cart and me pages. Added the preload attribute and set it to true. This means that when the App home page is loaded, Uniapp will automatically load these pages and cache them locally.

Next, we call uni.request in App.vue to implement the page preloading function:

<template>
  <div class="app">
    <uni-tab-bar :list="tabBar.list" :color="tabBar.color" :selected-color="tabBar.selectedColor" :background-color="tabBar.backgroundColor" :border-style="tabBar.borderStyle" @change="onTabChange"></uni-tab-bar>
  </div>
</template>

<script>
export default {
  data() {
    return {
      tabBar: uni.getStorageSync('tabBar') || {
        color: '#999999',
        selectedColor: '#000000',
        backgroundColor: '#ffffff',
        borderStyle: 'black',
        list: []
      },
      currentTab: 0
    }
  },
  onLoad() {
    uni.request({
      url: '/pages/me/me',
      method: 'GET',
      success: (res) => {
        uni.setStorageSync('/pages/me/me', res.data)
      }
    })
    uni.request({
      url: '/pages/cart/cart',
      method: 'GET',
      success: (res) => {
        uni.setStorageSync('/pages/cart/cart', res.data)
      }
    })
    uni.request({
      url: '/pages/category/category',
      method: 'GET',
      success: (res) => {
        uni.setStorageSync('/pages/category/category', res.data)
      }
    })
  },
  methods: {
    onTabChange(e) {
      const url = this.tabBar.list[e.index].pagePath
      this.currentTab = e.index
      uni.setStorageSync('currentTab', e.index)
      let pageData = uni.getStorageSync(url)
      if (!pageData) {
        uni.showLoading()
        // 发送请求获取数据
        uni.request({
          url: url,
          method: 'GET',
          success: (res) => {
            uni.hideLoading()
            pageData = res.data
            // 将获取的数据缓存到本地
            uni.setStorageSync(url, pageData)
          }
        })
      }
    }
  }
}
</script>
Copy after login

In the above code, we pass uni in the onLoad method of App.vue .request to obtain the data of category, cart and me pages and cache them locally.

When the TabBar menu item is clicked, we will obtain the corresponding page URL based on the menu item's index and check whether the page has been cached locally. If it is cached, the data is read directly from the cache and the page is rendered; if it is not cached, a GET request is sent to obtain the data and cached locally, and then the page is rendered.

The above is how to preload other TabBar pages in Uniapp. By preloading pages, we can quickly display the corresponding page when the user clicks the TabBar menu item to switch pages, thus improving the user experience.

The above is the detailed content of How does uniapp implement preloading of several other TabBar pages?. For more information, please follow other related articles on the PHP Chinese website!

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 admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the different types of testing that you can perform in a UniApp application? What are the different types of testing that you can perform in a UniApp application? Mar 27, 2025 pm 04:59 PM

The article discusses various testing types for UniApp applications, including unit, integration, functional, UI/UX, performance, cross-platform, and security testing. It also covers ensuring cross-platform compatibility and recommends tools like Jes

How can you reduce the size of your UniApp application package? How can you reduce the size of your UniApp application package? Mar 27, 2025 pm 04:45 PM

The article discusses strategies to reduce UniApp package size, focusing on code optimization, resource management, and techniques like code splitting and lazy loading.

What debugging tools are available for UniApp development? What debugging tools are available for UniApp development? Mar 27, 2025 pm 05:05 PM

The article discusses debugging tools and best practices for UniApp development, focusing on tools like HBuilderX, WeChat Developer Tools, and Chrome DevTools.

How can you use lazy loading to improve performance? How can you use lazy loading to improve performance? Mar 27, 2025 pm 04:47 PM

Lazy loading defers non-critical resources to improve site performance, reducing load times and data usage. Key practices include prioritizing critical content and using efficient APIs.

How can you optimize images for web performance in UniApp? How can you optimize images for web performance in UniApp? Mar 27, 2025 pm 04:50 PM

The article discusses optimizing images in UniApp for better web performance through compression, responsive design, lazy loading, caching, and using WebP format.

What are some common patterns for managing complex data structures in UniApp? What are some common patterns for managing complex data structures in UniApp? Mar 25, 2025 pm 02:31 PM

The article discusses managing complex data structures in UniApp, focusing on patterns like Singleton, Observer, Factory, and State, and strategies for handling data state changes using Vuex and Vue 3 Composition API.

What are computed properties in UniApp? How are they used? What are computed properties in UniApp? How are they used? Mar 25, 2025 pm 02:23 PM

UniApp's computed properties, derived from Vue.js, enhance development by providing reactive, reusable, and optimized data handling. They automatically update when dependencies change, offering performance benefits and simplifying state management co

How does UniApp handle global configuration and styling? How does UniApp handle global configuration and styling? Mar 25, 2025 pm 02:20 PM

UniApp manages global configuration via manifest.json and styling through app.vue or app.scss, using uni.scss for variables and mixins. Best practices include using SCSS, modular styles, and responsive design.

See all articles