頁面兩種跳轉方式
navigator和wxAPI
navigator組件
navigator組件主要是用于界面的跳轉
屬性:
target: 在哪個目標上發(fā)生跳轉, 默認當前小程序
url 當前小程序內的跳轉鏈接
open-type 跳轉方式
delta 當 open-type 為 'navigateBack' 時有效疲眷,表示回退的層數(shù)
使用方式
基本使用方式
<navigator url="/pages/about/about">跳到關于頁面</navigator>
跳轉到關于頁面, 左上角有返回按鈕
open-type屬性:
redurect
<navigator url="/pages/about/about" open-type="redirect">跳到關于頁面(redirect)</navigator>
關閉當前頁面, 跳到關于頁面, 不允許跳轉到tabbar頁面, 不能反回, 安卓手機反回直接退出小程序
switchTab
switchTab:跳轉到 tabBar 頁面败玉,并關閉其他所有非 tabBar 頁面郭毕。(需要在tabBar中定義的)
<navigator url="/pages/detail/detail" open-type="switchTab">跳到詳情頁面(switchTab)</navigator>
app.json:
"tabBar": {
"list": [
{
"pagePath": "pages/home/home",
"text": "首頁"
},
{
"pagePath": "pages/detail/detail",
"text": "詳情"
},
{
"pagePath": "pages/about/about",
"text": "關于"
}
]
}
reLaunch
關閉所有的頁面奔坟,打開應用中某個頁面湘换。(直接展示某個頁面狂秘,并且可以跳轉到tabBar頁面)
效果與redirect類似
navigateBack
關閉當前頁面嫩挤,返回上一頁面或多級頁面』娉粒可通過 getCurrentPages
獲取當前的頁面棧煎楣,決定需要返回幾層。
當使用redirect
和reLaunch
關閉頁面時, getCurrentPages
無效
open-type:navigateBack(表示該navigator組件用于返回)
delta:返回的層級(指定返回的層級车伞,open-type必須是navigateBack才生效)
about.wxml
<navigator open-type="navigateBack" delta="2">跳到關于頁面</navigator>
數(shù)據(jù)傳遞-傳遞方式分析
如果在界面跳轉過程中我們需要相互傳遞一些數(shù)據(jù)择懂,應該如何完成呢?
- 首頁 -> 詳情頁:使用URL中的query字段
- 詳情頁 -> 首頁:在詳情頁內部拿到首頁的頁面對象另玖,直接修改數(shù)據(jù)
數(shù)據(jù)傳遞過程
home頁面?zhèn)鬟f數(shù)據(jù)給其他待跳轉頁面
home.wxml
<navigator url="/pages/about/about?key=hello"><button>跳到關于頁面</button></navigator>
url參數(shù)后面的查詢字符串會被子頁面直接接收
about.js
onLoad:function(options){
console.log(options)
}
控制臺會打印出: {key: "hello"}
子頁面?zhèn)鬟f數(shù)據(jù)給home頁面
如果是監(jiān)聽按鈕或者navigator的點擊來返回時, 可以通過bindtap調用函數(shù)完成.
但是這種方式不能監(jiān)聽左上角返回按鈕的點擊.所以我們選擇在onUnload中修改數(shù)據(jù)
小程序并沒有提供直接修改數(shù)據(jù)的方法.
可以通過getCurrentPages來獲取所有的頁面, 然后使用頁面對象的setData({})函數(shù)來修改
about頁面退出時, home頁面message數(shù)據(jù)會被改變
home.js
data:{
message: '哈哈哈'
}
about.js
// 頁面退出時調用
onUnload: function(){
let pages = getCurrentPages() // 獲取當前所有的頁面
let home = pages[pages.length - 2]
home.setData({
message: '嘿嘿嘿'
})
}
微信API跳轉
使用微信提供的API也可以實現(xiàn)頁面的跳轉
- wx.navigateTo
- wx.switchTab
- wx.reLaunch
- wx.redirectTo
- wx.navigateBack
跳轉:
home.wxml
<button bind:tap="handlePushAbout">wxAPI跳轉</button>
home.js
handlePushAbout(){
wx.navigateTo({
url: '/pages/about/about?key=value',
})
}
返回:
about.wxml
<button bind:tap="backHome">返回主頁</button>
about.js
backHome(){
wx.navigateBack({
delta: '1' // 返回的頁面數(shù)困曙,如果 delta 大于現(xiàn)有頁面數(shù),則返回到首頁谦去。
})
}