/**
* 设置主题色
* @param state
* @param val
*/
setThemeColor (state, val) {
state.themeColor = val;
// 在H5环境中更新CSS变量
// #ifdef H5
const root = document.documentElement;
if (root) {
root.style.setProperty('--theme-color', state.themeColor);
}
// #endif
// 在App环境中更新CSS变量
// #ifdef APP-PLUS
try {
plus.navigator.setStatusBarStyle("UIStatusBarStyleBlackOpaque");
// 设置CSS变量 - 使用更兼容的方式
const webView = plus.webview.currentWebview();
if (webView) {
// 通过evalJS设置CSS变量
const script = `document.documentElement.style.setProperty('--theme-color', '${state.themeColor}');
`;
webView.evalJS(script);
}
// 同时更新所有已打开的webview
const webviews = plus.webview.all();
webviews.forEach(view => {
const updateScript = `document.documentElement.style.setProperty('--theme-color', '${state.themeColor}');
`;
view.evalJS(updateScript);
});
} catch (error) {
console.warn('设置App主题色失败:', error);
}
// #endif
}
// 使用方法 app.vue onShow 的时候进行调用
commt('setThemeColor',"#165DFF")
// 注意事项,发现app 中切换页面的时候,无效
app.vue methods 中添加路由监听方法
/**
- 监听路由变化
*/
async watchRouter() {
const that = this;
let RouterTypes = ['navigateTo', 'redirectTo', 'switchTab', 'navigateBack', 'reLaunch'];
RouterTypes.forEach(item => {
console.log("App watchRouter=", item);
uni.addInterceptor(item, {
invoke(e) {
console.log("App watchRouter invoke=", e,e.url);
},
success(e) {
setTimeout(() => {
// #ifdef APP-PLUS
that.$store.commit("setThemeColor", that.$store.state.themeColor);
// #endif
}, 500); // 延迟确保页面加载完成
}
});
})
},
Azikou
哥,你能展开说说,写个大致的示例嘛。。我这个变量问题纠结好几天了。
2024-08-21 08:53