目錄
- 問題示例代碼
- 解決思路1(缺點影響顯示效果有延遲)
- 解決思路2——通過路由刷新頁面(缺點只適用于部分網頁)
- 解決思路3——vuex(沒學會~)
- 總結
歡迎關注 『uniapp』 專欄,持續更新中
歡迎關注 『uniapp』 專欄,持續更新中
問題示例代碼
我這個業務場景是在跟隨系統主題(深色/淺色模式)的情況下 用戶在設置中修改了主題后app自動適應主題。
開啟了主題監聽
uni.onThemeChange(({theme}) => {console.log('onThemeChange', theme)uni.setStorageSync('sys_theme', theme)if (uni.getStorageSync('theme_isAuto')) {uni.setStorageSync('theme_mode', theme)}})
在onshow中根據讀取的主題設置顏色樣式
this.theme_mode = uni.getStorageSync('theme_mode')//設置頂部導航背景顏色this.navbarBackground = {background: this.theme_mode === 'dark' ? this.themeConfig.dark.navBgColor : this.themeConfig.light.navBgColor};//頂部導航字體顏色this.navTxtStyle = this.theme_mode === 'dark' ? this.themeConfig.dark.navTxtStyle : this.themeConfig.light.navTxtStyle;console.log('ok', this.theme)
排查了半天bug最后發現輸出日志的結果
'ok', this.theme
'theme_mode', theme
也就是我們的onshow都執行完畢了,onThemeChange才姍姍來遲,當然無法成功渲染頁面。
解決思路1(缺點影響顯示效果有延遲)
延遲執行,雖然很low,但是一步到位。(我最后才想到這個辦法~)最關鍵的是之前試了沒有成功,一直以為不可行,后來發現是因為沒有把this.theme_mode = uni.getStorageSync('theme_mode')
放到setTimeout里面。
setTimeout(() => {this.theme_mode = uni.getStorageSync('theme_mode')//設置頂部導航背景顏色this.navbarBackground = {background: this.theme_mode === 'dark' ? this.themeConfig.dark.navBgColor : this.themeConfig.light.navBgColor};//頂部導航字體顏色this.navTxtStyle = this.theme_mode === 'dark' ? this.themeConfig.dark.navTxtStyle : this.themeConfig.light.navTxtStyle;}, 100);
解決思路2——通過路由刷新頁面(缺點只適用于部分網頁)
本質是用uni.reLaunch
頁面跳轉,而且會導致你無法跳轉回原來的網頁
在app.vue的onLaunch中
onLaunch() {uni.onThemeChange(({ theme }) => {console.log('onThemeChange', theme);// 觸發路由刷新this.refreshPageRoute();});},
在app.vue的methods中
// 觸發路由刷新的方法
refreshPageRoute() {// 獲取當前頁面路由路徑const pages = getCurrentPages();const currentPage = pages[pages.length - 1];const route = currentPage.route;console.log(`/${route}`); // 注意使用反引號(`)來實現字符串插值// 使用 uni.reLaunch 方法刷新當前頁面uni.reLaunch({url: `/${route}`});
}
解決思路3——vuex(沒學會~)
使用 Vuex 管理狀態: 如果你的應用使用了 Vuex 來管理全局狀態,你可以在主題變化時更新一個全局狀態,然后在需要更新的頁面中監聽這個狀態的變化,在變化時手動調用 onShow 方法。
總結
大家喜歡的話,給個👍,點個關注!給大家分享更多計算機專業學生的求學之路!
版權聲明:
發現你走遠了@mzh原創作品,轉載必須標注原文鏈接
Copyright 2024 mzh
Crated:2024-4-1
歡迎關注 『uniapp』 專欄,持續更新中
歡迎關注 『uniapp』 專欄,持續更新中
『未完待續』