1. 程式人生 > >微信小程式之路由

微信小程式之路由

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();
            }
        })
    },

})