小程序模板網(wǎng)

微信小程序路由詳解

發(fā)布時(shí)間:2021-06-07 08:49 所屬欄目:小程序開發(fā)教程

1. 路由方式

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

用法如下:

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

2. 路由傳參

從列表頁進(jìn)入詳情頁時(shí),需要傳遞列表被點(diǎn)擊項(xiàng)目的 id 至詳情頁,方法:

  1. 在列表頁通過data-id='{{item.id}}'給各個(gè)項(xiàng)目綁定一個(gè) 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>
// 進(jìn)入詳情頁時(shí) 傳遞 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();
            }
        })
    },

})


易優(yōu)小程序(企業(yè)版)+靈活api+前后代碼開源 碼云倉庫:starfork
本文地址:http://www.u-renovate.com/wxmini/doc/course/26100.html 復(fù)制鏈接 如需定制請聯(lián)系易優(yōu)客服咨詢:800182392 點(diǎn)擊咨詢
QQ在線咨詢
AI智能客服 ×