Skip to content

Navigation Components

Navigation components are used to implement page navigation and routing functionality in uni-app applications.

The navigator component is used for page navigation, similar to the HTML <a> tag but with more powerful functionality.

Basic Usage

vue
<template>
  <view>
    <!-- Basic navigation -->
    <navigator url="/pages/detail/detail">Go to Detail Page</navigator>
    
    <!-- Navigation with parameters -->
    <navigator url="/pages/detail/detail?id=123&name=test">
      Go to Detail with Parameters
    </navigator>
    
    <!-- Tab navigation -->
    <navigator url="/pages/home/home" open-type="switchTab">
      Switch to Home Tab
    </navigator>
    
    <!-- Redirect navigation -->
    <navigator url="/pages/login/login" open-type="redirect">
      Redirect to Login
    </navigator>
  </view>
</template>

Properties

PropertyTypeDefaultDescription
urlStringTarget page path
open-typeStringnavigateNavigation type
deltaNumber1Number of pages to go back (when open-type="navigateBack")
app-idStringTarget mini-program appId (mini-program only)
pathStringTarget mini-program page path (mini-program only)
extra-dataObjectExtra data passed to target mini-program (mini-program only)
versionStringreleaseTarget mini-program version (mini-program only)
hover-classStringnavigator-hoverStyle class when pressed
hover-stop-propagationBooleanfalseWhether to stop hover event propagation
hover-start-timeNumber50Time delay before hover state starts (ms)
hover-stay-timeNumber600Time to keep hover state after release (ms)
targetStringselfNavigation target (mini-program only)

open-type Values

ValueDescriptionPlatform Support
navigateNavigate to new pageAll
redirectRedirect to new pageAll
switchTabSwitch to tab pageAll
reLaunchClose all pages and navigate to new pageAll
navigateBackGo back to previous pageAll
navigateToMiniProgramNavigate to other mini-programMini-program
exitExit mini-programMini-program

Events

EventDescriptionParameters
@successTriggered when navigation succeedsevent
@failTriggered when navigation failsevent
@completeTriggered when navigation completesevent

Advanced Examples

vue
<template>
  <view class="container">
    <!-- Navigation with custom hover effect -->
    <navigator 
      url="/pages/profile/profile"
      hover-class="custom-hover"
      hover-start-time="100"
      hover-stay-time="300"
    >
      <view class="nav-item">
        <image src="/static/icons/profile.png" class="nav-icon"></image>
        <text class="nav-text">Profile</text>
      </view>
    </navigator>
    
    <!-- Navigate to mini-program -->
    <navigator
      app-id="wx1234567890"
      path="pages/index/index"
      open-type="navigateToMiniProgram"
      :extra-data="extraData"
      version="release"
      @success="onNavigateSuccess"
      @fail="onNavigateFail"
    >
      Open Other Mini-Program
    </navigator>
    
    <!-- Go back with custom delta -->
    <navigator open-type="navigateBack" :delta="2">
      Go Back 2 Pages
    </navigator>
  </view>
</template>

<script>
export default {
  data() {
    return {
      extraData: {
        userId: '123',
        source: 'myapp'
      }
    }
  },
  methods: {
    onNavigateSuccess(e) {
      console.log('Navigation success:', e);
    },
    onNavigateFail(e) {
      console.log('Navigation failed:', e);
    }
  }
}
</script>

<style>
.nav-item {
  display: flex;
  align-items: center;
  padding: 20rpx;
  border: 1px solid #e0e0e0;
  border-radius: 8rpx;
}

.nav-icon {
  width: 40rpx;
  height: 40rpx;
  margin-right: 20rpx;
}

.nav-text {
  font-size: 32rpx;
  color: #333;
}

.custom-hover {
  background-color: #f0f0f0;
  opacity: 0.8;
}
</style>

Programmatic Navigation

In addition to using the navigator component, you can also use uni-app's navigation APIs for programmatic navigation.

uni.navigateTo()

Navigate to a new page while keeping the current page in the page stack.

javascript
// Basic navigation
uni.navigateTo({
  url: '/pages/detail/detail'
});

// Navigation with parameters
uni.navigateTo({
  url: '/pages/detail/detail?id=123&name=test',
  success: (res) => {
    console.log('Navigation success');
  },
  fail: (err) => {
    console.log('Navigation failed:', err);
  }
});

// Navigation with animation (App only)
uni.navigateTo({
  url: '/pages/detail/detail',
  animationType: 'slide-in-right',
  animationDuration: 300
});

uni.redirectTo()

Close the current page and navigate to a new page.

javascript
uni.redirectTo({
  url: '/pages/login/login'
});

uni.reLaunch()

Close all pages and navigate to a new page.

javascript
uni.reLaunch({
  url: '/pages/home/home'
});

uni.switchTab()

Switch to a tab page and close all other non-tab pages.

javascript
uni.switchTab({
  url: '/pages/home/home'
});

uni.navigateBack()

Go back to the previous page.

javascript
// Go back one page
uni.navigateBack();

// Go back multiple pages
uni.navigateBack({
  delta: 2
});

1. Choose the Right Navigation Method

javascript
// Use navigateTo for detail pages
uni.navigateTo({
  url: '/pages/detail/detail?id=123'
});

// Use redirectTo for login/logout scenarios
uni.redirectTo({
  url: '/pages/login/login'
});

// Use switchTab for tab navigation
uni.switchTab({
  url: '/pages/home/home'
});

// Use reLaunch for complete app restart
uni.reLaunch({
  url: '/pages/welcome/welcome'
});

2. Parameter Passing

javascript
// Method 1: URL parameters
uni.navigateTo({
  url: '/pages/detail/detail?id=123&type=product'
});

// In target page
export default {
  onLoad(options) {
    console.log('Received parameters:', options);
    // options: { id: '123', type: 'product' }
  }
}

// Method 2: Using eventChannel (recommended for complex data)
uni.navigateTo({
  url: '/pages/detail/detail',
  success: (res) => {
    res.eventChannel.emit('acceptDataFromOpenerPage', {
      data: complexData
    });
  }
});

// In target page
export default {
  onLoad() {
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on('acceptDataFromOpenerPage', (data) => {
      console.log('Received complex data:', data);
    });
  }
}

3. Navigation Guards

javascript
// Global navigation guard
// App.vue
export default {
  onLaunch() {
    // Override uni.navigateTo to add global logic
    const originalNavigateTo = uni.navigateTo;
    uni.navigateTo = (options) => {
      // Check authentication
      if (this.needsAuth(options.url) && !this.isLoggedIn()) {
        uni.redirectTo({
          url: '/pages/login/login'
        });
        return;
      }
      
      // Call original method
      return originalNavigateTo(options);
    };
  },
  methods: {
    needsAuth(url) {
      const authPages = ['/pages/profile/', '/pages/order/'];
      return authPages.some(page => url.includes(page));
    },
    isLoggedIn() {
      return !!uni.getStorageSync('token');
    }
  }
}

Platform Differences

Mini-Program Specific Features

vue
<template>
  <!-- Navigate to other mini-programs -->
  <navigator
    app-id="wxd678efh567hg6787"
    path="pages/index/index"
    open-type="navigateToMiniProgram"
    version="release"
    :extra-data="{ from: 'myapp' }"
  >
    Open Other Mini-Program
  </navigator>
  
  <!-- Exit mini-program -->
  <navigator open-type="exit">
    Exit Mini-Program
  </navigator>
</template>

App Specific Features

javascript
// App-specific navigation with animations
// #ifdef APP-PLUS
uni.navigateTo({
  url: '/pages/detail/detail',
  animationType: 'slide-in-right',
  animationDuration: 300
});
// #endif

// Native navigation bar customization
// #ifdef APP-PLUS
plus.webview.currentWebview().setStyle({
  titleNView: {
    backgroundColor: '#007AFF',
    titleText: 'Custom Title',
    titleColor: '#FFFFFF'
  }
});
// #endif

H5 Specific Features

javascript
// H5 browser history management
// #ifdef H5
// Use browser's back button
window.addEventListener('popstate', (e) => {
  console.log('Browser back button pressed');
});

// Modify browser URL without navigation
history.pushState(null, null, '/new-url');
// #endif

Common Issues and Solutions

1. Navigation Not Working

javascript
// Problem: Navigation doesn't work
// Solution: Check if the target page exists in pages.json

// pages.json
{
  "pages": [
    {
      "path": "pages/index/index"
    },
    {
      "path": "pages/detail/detail"  // Make sure this exists
    }
  ]
}

2. Parameters Not Received

javascript
// Problem: Parameters not received in target page
// Solution: Use onLoad instead of created/mounted

export default {
  // Wrong
  created() {
    console.log(this.$route.query); // May be undefined
  },
  
  // Correct
  onLoad(options) {
    console.log(options); // Parameters are available here
  }
}

3. Tab Navigation Issues

javascript
// Problem: switchTab doesn't work
// Solution: Make sure the target page is configured as a tab page

// pages.json
{
  "tabBar": {
    "list": [
      {
        "pagePath": "pages/home/home",  // Must match exactly
        "text": "Home"
      }
    ]
  }
}

// Use switchTab for tab pages
uni.switchTab({
  url: '/pages/home/home'  // Must start with '/'
});

Summary

Navigation components and APIs are essential for creating smooth user experiences in uni-app applications. Key points to remember:

  1. Use the appropriate navigation method for different scenarios
  2. Handle parameters correctly using onLoad
  3. Consider platform-specific features and limitations
  4. Implement proper error handling and user feedback
  5. Test navigation flows on all target platforms

For more information about navigation, refer to the uni-app official documentation.

一次开发,多端部署 - 让跨平台开发更简单