羅湖做網(wǎng)站多少錢域名搜索
微信小程序的路由系統(tǒng)和其他Web應(yīng)用類似,主要通過頁面路徑和URL參數(shù)進行頁面導(dǎo)航和數(shù)據(jù)傳遞。下面詳細介紹微信小程序路由的基本使用方法和相關(guān)技巧。
1. 基本頁面導(dǎo)航
1.1 配置頁面路徑
在微信小程序的 app.json
文件中,需要配置小程序的頁面路徑。這里定義了小程序中包含的所有頁面路徑。
{"pages": ["pages/index/index","pages/detail/detail"]
}
1.2 使用導(dǎo)航 API 跳轉(zhuǎn)頁面
微信小程序提供了多種導(dǎo)航 API,可以在頁面之間進行跳轉(zhuǎn)。
wx.navigateTo | 保留當(dāng)前頁面,跳轉(zhuǎn)到應(yīng)用內(nèi)的某個頁面,使用 wx.navigateBack 可以返回到原頁面 |
wx.redirectTo | 關(guān)閉當(dāng)前頁面,跳轉(zhuǎn)到應(yīng)用內(nèi)的某個頁面 |
wx.switchTab | 跳轉(zhuǎn)到指定的 tabBar 頁面,并關(guān)閉其他所有非 tabBar 頁面 |
wx.reLaunch | 關(guān)閉所有頁面,打開到應(yīng)用內(nèi)的某個頁面 |
?
?
例子:使用 wx.navigateTo
跳轉(zhuǎn)頁面
wx.navigateTo({url: '/pages/detail/detail?id=123&name=John'
});
2. URL 參數(shù)傳遞
2.1 傳遞參數(shù)
在跳轉(zhuǎn)頁面時,可以在 URL 中附加參數(shù),例如上面的例子中,我們在 URL 中附加了 id
和 name
參數(shù)。
2.2 獲取參數(shù)
在目標(biāo)頁面的 onLoad
方法中,可以通過 options
參數(shù)獲取傳遞過來的參數(shù):
Page({onLoad: function (options) {console.log(options.id); // 輸出 123console.log(options.name); // 輸出 John}
});
3. 動態(tài)構(gòu)建 URL 參數(shù)
有時需要傳遞動態(tài)生成的參數(shù),可以通過字符串拼接或模板字符串來實現(xiàn):
const id = 123;
const name = 'John';
wx.navigateTo({url: `/pages/detail/detail?id=${id}&name=${name}`
});
4. 復(fù)雜數(shù)據(jù)傳遞
如果需要傳遞復(fù)雜的數(shù)據(jù)(例如對象或數(shù)組),可以將數(shù)據(jù)轉(zhuǎn)換為 JSON 字符串傳遞,并在目標(biāo)頁面進行解析。
4.1 傳遞 JSON 字符串
const data = {id: 123,name: 'John',items: [1, 2, 3]
};
wx.navigateTo({url: `/pages/detail/detail?data=${encodeURIComponent(JSON.stringify(data))}`
});
4.2 解析 JSON 字符串
在目標(biāo)頁面中,通過 decodeURIComponent
和 JSON.parse
解析數(shù)據(jù):
Page({onLoad: function (options) {const data = JSON.parse(decodeURIComponent(options.data));console.log(data.id); // 輸出 123console.log(data.name); // 輸出 Johnconsole.log(data.items);// 輸出 [1, 2, 3]}
});
5. 使用全局數(shù)據(jù)或本地存儲
當(dāng)傳遞的數(shù)據(jù)過大或復(fù)雜時,URL 參數(shù)可能不是最佳選擇??梢允褂萌謹?shù)據(jù)或本地存儲。
5.1 使用全局數(shù)據(jù)
在 app.js
中定義全局數(shù)據(jù):
App({globalData: {userInfo: null}
});
在頁面中設(shè)置和獲取全局數(shù)據(jù):
// 設(shè)置全局數(shù)據(jù)
const app = getApp();
app.globalData.userInfo = {id: 123,name: 'John'
};// 獲取全局數(shù)據(jù)
Page({onLoad: function () {const app = getApp();const userInfo = app.globalData.userInfo;console.log(userInfo.id); // 輸出 123console.log(userInfo.name); // 輸出 John}
});
5.2 使用本地存儲
通過 wx.setStorageSync
和 wx.getStorageSync
來存儲和獲取數(shù)據(jù):
// 設(shè)置本地存儲
wx.setStorageSync('userInfo', {id: 123,name: 'John'
});// 獲取本地存儲
Page({onLoad: function () {const userInfo = wx.getStorageSync('userInfo');console.log(userInfo.id); // 輸出 123console.log(userInfo.name); // 輸出 John}
});