微信小程序之路由


1. 路由方式

路由方式 觸發時機 路由前頁面 路由后頁面
初始化 小程序打開的第一個頁面 onLoad, onShow
打開新頁面 調用 API wx.navigateTo 或使用組件 onHide onLoad, onShow
頁面重定向 調用 API wx.redirectTo 或使用組件 onUnload onLoad, onShow
頁面返回 調用 API wx.navigateBack 或使用組件 或用戶按左上角返回按鈕 onUnload onShow
Tab 切換 調用 API wx.switchTab 或使用組件 或用戶切換 Tab 各種情況請參考下表
重啟動 調用 API wx.reLaunch 或使用組件 onUnload onLoad, onShow

用法如下:

<navigator url="/pages/detail/detail" open-type='navigate' style='border:1px solid red;' >進入非tab頁</navigator>
<navigator url="/pages/index/index" open-type='switchTab' >進入首頁(tab頁)</navigator>
<navigator url="/pages/index/index" open-type='switchTab' >進入首頁(tab頁)</navigator>
<navigator open-type='navigateBack' >回退</navigator>
  • navigateTo, redirectTo 只能打開非 abBar 頁面。
  • switchTab 只能打開 tabBar 頁面。
  • reLaunch可以打開任意頁面, 但是沒有返回按鈕,需要定義一個可以點擊回退的按鈕。
  • 頁面底部的 tabBar 由頁面決定,即只要是定義為 tabBar 的頁面,底部都有 tabBar。
  • 調用頁面路由帶的參數可以在目標頁面的onLoad中獲取。

2. 路由傳參

從列表頁進入詳情頁時,需要傳遞列表被點擊項目的 id 至詳情頁,方法:

  1. 在列表頁通過data-id='{{item.id}}'給各個項目綁定一個 id ;
  2. 在詳情頁通過 onload 拿到 id;
列表頁:
<view class="list" >
    <view class='box'  wx:for='{{list}}' wx:key='{{index}}' data-id='{{item.id}}' bindtap='goDetail'>
        <image src='{{item.img}}'></image>
        <view class='tip'>
            <text>{{item.title}}</text>
            <text class='price'>¥{{item.price}}</text>
        </view> 
    </view> 
</view>
// 進入詳情頁時 傳遞 id
goDetail (e) {
    console.log(e.currentTarget.dataset.id),
    wx.navigateTo({
        url: `/pages/detail/detail?id=${e.currentTarget.dataset.id}`,
    })
},
詳情頁:
// pages/detail/detail.js
Page({
 
    data: {
        detail: {},
        loading: true
    }, 
    
    onLoad: function (options) {
        this.loadDetail(options.id); // 拿到列表頁傳過來的 id
        console.log(options.id)
    },

    loadDetail (id) {
        wx.showLoading({
            title: '詳情加載中...',
        })

        wx.request({
            url: 'http://10.0.1.109:3000/list',
            success: (res) => {
                console.log(res.data.cityList);
                let thisPlace = res.data.cityList.filter((val) => val.id == id)
                console.log(thisPlace)
                this.setData({ 
                    detail: thisPlace[0],
                    loading: false
                });
                console.log(this.data.detail)
                wx.hideLoading();
            }
        })
    },

})


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM