| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493 |
- <template>
- <div id="app">
- <!-- 错误边界 -->
- <div v-if="hasError" class="error-boundary">
- <h2>应用遇到问题</h2>
- <p>{{ errorMessage }}</p>
- <button @click="reloadApp">重新加载</button>
- </div>
-
- <!-- 正常内容 -->
- <div v-else>
- <!-- 顶部菜单栏 -->
- <div v-if="showHeader" class="app-header">
- <router-link to="/">首页</router-link>
- <router-link to="/pages/novel/list">小说列表</router-link>
- <router-link to="/pages/author/apply">作者申请</router-link>
- <router-link to="/pages/search/index">搜索</router-link>
- </div>
-
- <!-- 主内容区 -->
- <router-view v-if="isRouterAlive" />
-
- <!-- 使用自定义TabBar组件 -->
- <CustomTabbar v-if="showTabBar" />
- </div>
- </div>
- </template>
-
- <script>
- import CustomTabbar from '@/components/custom-tabbar/index.vue';
-
- export default {
- name: 'App',
- provide() {
- return {
- reload: this.reload
- }
- },
- components: { CustomTabbar },
- data() {
- return {
- hasError: false,
- errorMessage: '',
- isRouterAlive: true,
- showTabBar: false,
- showHeader: false,
- isMounted: false,
- tabBarPages: [
- '/pages/index/index',
- '/pages/novel/list',
- '/pages/bookshelf/index',
- '/pages/me/index'
- ],
- hideMenuRoutes: [
- '/login',
- '/register',
- '/forgot-password',
- '/novel/reader'
- ]
- }
- },
- mounted() {
- console.log('UniApp SDK版本:', uni.getSystemInfoSync().SDKVersion);
- console.log('平台:', uni.getSystemInfoSync().platform);
-
- this.isMounted = true;
- this.checkEnvironment();
- this.checkRouteAuth();
- this.initTheme();
- this.initStoreState();
- this.safeUpdateMenuVisibility();
-
- // 添加全局错误处理
- window.addEventListener('error', (event) => {
- console.error('全局错误捕获:', event.error);
- this.logError(event.error);
- });
-
- window.addEventListener('unhandledrejection', (event) => {
- console.error('未处理的Promise拒绝:', event.reason);
- this.logError(event.reason);
- });
- },
- errorCaptured(err, vm, info) {
- // 捕获子组件错误
- console.error('Error captured:', err, info);
- this.hasError = true;
- this.errorMessage = err.message;
-
- // 阻止错误继续向上传播
- return false;
- },
- beforeDestroy() {
- this.isMounted = false;
- },
- watch: {
- '$route': {
- immediate: true,
- handler(newRoute) {
- if (this.isMounted && newRoute && newRoute.path) {
- this.safeUpdateMenuVisibility();
- }
- }
- },
- '$store.state.token': {
- handler(newToken) {
- if (newToken) {
- console.log('检测到新token,重新加载数据');
- this.reloadData();
- }
- },
- immediate: true
- }
- },
- methods: {
- checkPagePaths() {
- // 获取所有已注册的页面路径
- const pages = getCurrentPages();
- console.log('当前页面栈:', pages);
-
- // 检查reader页面是否存在
- const readerPageExists = pages.some(page =>
- page.route.includes('novel/reader')
- );
- console.log('Reader页面是否存在:', readerPageExists);
- },
- // 环境检查方法
- checkEnvironment() {
- console.log('开始环境检查...');
- // 检查uni对象
- if (typeof uni === 'undefined') {
- console.error('uni对象未定义,uni-app环境可能未正确初始化');
- this.injectFallbackUni();
- return;
- }
-
- // 检查uni.navigateTo方法
- if (typeof uni.navigateTo !== 'function') {
- console.error('uni.navigateTo方法不存在');
- this.injectFallbackUni();
- return;
- }
-
- // 检查其他必要的uni API
- const requiredMethods = ['showToast', 'navigateBack', 'redirectTo'];
- requiredMethods.forEach(method => {
- if (typeof uni[method] !== 'function') {
- console.warn(`uni.${method}方法不存在`);
- }
- });
-
- console.log('环境检查完成');
- },
-
- // 注入备用uni对象
- injectFallbackUni() {
- console.log('注入备用uni对象');
-
- // 确保window.uni存在
- if (typeof window !== 'undefined' && typeof window.uni === 'undefined') {
- window.uni = {
- navigateTo: (options) => {
- console.log('备用navigateTo被调用:', options);
- if (options && options.url) {
- // 使用Vue Router进行跳转
- if (this.$router && typeof this.$router.push === 'function') {
- const path = options.url.split('?')[0];
- const query = {};
-
- if (options.url.includes('?')) {
- const queryString = options.url.split('?')[1];
- queryString.split('&').forEach(param => {
- const [key, value] = param.split('=');
- query[key] = decodeURIComponent(value);
- });
- }
-
- this.$router.push({
- path: path,
- query: query
- });
- } else {
- // 降级到window.location
- window.location.href = options.url;
- }
- }
- },
- showToast: (options) => {
- console.log('备用showToast被调用:', options);
- alert(options.title || '提示信息');
- },
- // 添加其他必要的方法
- navigateBack: () => {
- if (this.$router && typeof this.$router.back === 'function') {
- this.$router.back();
- } else {
- window.history.back();
- }
- },
- redirectTo: (options) => {
- if (options && options.url) {
- if (this.$router && typeof this.$router.replace === 'function') {
- const path = options.url.split('?')[0];
- const query = {};
-
- if (options.url.includes('?')) {
- const queryString = options.url.split('?')[1];
- queryString.split('&').forEach(param => {
- const [key, value] = param.split('=');
- query[key] = decodeURIComponent(value);
- });
- }
-
- this.$router.replace({
- path: path,
- query: query
- });
- } else {
- window.location.replace(options.url);
- }
- }
- },
- getStorageSync: (key) => {
- return localStorage.getItem(key);
- },
- setStorageSync: (key, value) => {
- localStorage.setItem(key, value);
- }
- };
- }
- },
-
- // 错误日志记录
- logError(error) {
- // 这里可以添加错误上报逻辑
- console.error('记录错误:', error);
-
- // 如果是导航相关错误,尝试修复
- if (error.message && error.message.includes('navigate')) {
- this.injectFallbackUni();
- }
- },
-
- // 平台检测
- checkPlatform() {
- // 检测运行平台
- const platform = this.getPlatform();
- console.log('当前运行平台:', platform);
-
- // 根据不同平台采取不同策略
- if (platform === 'h5') {
- this.initH5Environment();
- } else if (platform === 'weapp') {
- this.initWeappEnvironment();
- } else {
- this.initDefaultEnvironment();
- }
- },
-
- getPlatform() {
- // 判断当前运行环境
- if (typeof wx !== 'undefined' && wx && wx.request) {
- return 'weapp'; // 微信小程序
- } else if (typeof window !== 'undefined' && window.document) {
- return 'h5'; // H5环境
- } else if (typeof plus !== 'undefined') {
- return 'app'; // 5+App环境
- }
- return 'unknown';
- },
-
- initH5Environment() {
- console.log('初始化H5环境');
- // H5环境特定初始化
- },
-
- initWeappEnvironment() {
- console.log('初始化微信小程序环境');
- // 微信小程序环境特定初始化
- },
-
- initDefaultEnvironment() {
- console.log('初始化默认环境');
- // 默认环境初始化
- },
-
- // 确保 initTheme 方法正确定义
- initTheme() {
- console.log('主题初始化开始');
-
- // 设置默认主题
- const themeName = localStorage.getItem('selectedTheme') || 'aydzBlue';
- // 应用主题变量
- const themes = {
- aydzBlue: {
- '--primary-color': '#2a5caa',
- '--bg-color': '#e6f7ff',
- '--text-color': '#1a3353',
- '--card-bg': '#d0e8ff',
- '--header-bg': '#2a5caa'
- },
- default: {
- '--primary-color': '#1890ff',
- '--bg-color': '#f8f9fa',
- '--text-color': '#333',
- '--card-bg': '#ffffff'
- }
- };
- const theme = themes[themeName] || themes.default;
-
- // 应用主题变量
- Object.keys(theme).forEach(key => {
- document.documentElement.style.setProperty(key, theme[key]);
- });
-
- console.log('主题初始化完成');
- },
-
- reload() {
- this.isRouterAlive = false;
- this.$nextTick(() => {
- this.isRouterAlive = true;
- this.safeUpdateMenuVisibility();
- });
- },
- reloadApp() {
- this.hasError = false;
- this.isRouterAlive = false;
- this.$nextTick(() => {
- this.isRouterAlive = true;
- });
- },
- safeUpdateMenuVisibility() {
- // 确保组件已挂载且路由对象存在
- if (!this.isMounted || !this.$route || !this.$route.path) return;
-
- const currentPath = this.$route.path;
-
- // 检查是否显示底部TabBar
- this.showTabBar = this.tabBarPages.some(path =>
- currentPath.includes(path) || currentPath === path
- );
-
- // 检查是否显示顶部菜单
- this.showHeader = !this.hideMenuRoutes.some(route =>
- currentPath.includes(route) || currentPath === route
- );
- },
-
- initStoreState() {
- // 使用备用存储方法
- const token = (uni && uni.getStorageSync) ? uni.getStorageSync('token') : localStorage.getItem('token') || '';
- const readingProgress = (uni && uni.getStorageSync) ? uni.getStorageSync('readingProgress') : localStorage.getItem('readingProgress') || 1;
-
- // 确保 store 存在并正确提交
- if (this.$store) {
- this.$store.commit('SET_TOKEN', token);
- this.$store.commit('SET_READING_PROGRESS', readingProgress);
- console.log('Store initialized:', this.$store.state);
- } else {
- console.error('Store is not available!');
- }
- },
-
- checkRouteAuth() {
- // 简单的路由权限检查
- if (!this.$route || !this.$route.path) return;
-
- const authRequiredRoutes = [
- '/pages/author/apply',
- '/pages/bookshelf/index',
- '/pages/me/index'
- ];
-
- if (authRequiredRoutes.some(route => this.$route.path.includes(route))) {
- if (!this.$store.getters.token) {
- // 使用统一的提示方法
- if (uni && uni.showToast) {
- uni.showToast({ title: '请先登录', icon: 'none' });
- } else {
- alert('请先登录');
- }
-
- if (this.$router) {
- this.$router.push('/pages/login/index');
- } else if (uni && uni.navigateTo) {
- uni.navigateTo({ url: '/pages/login/index' });
- }
- }
- }
- },
-
- reloadData() {
- // 在需要的地方调用此方法重新加载数据
- if (this.$route.path === '/pages/novel/list') {
- this.$refs.novelList?.initData?.();
- }
- }
- }
- }
- </script>
-
- <style lang="scss">
- @import '@/styles/index.scss';
-
- /* 全局样式修复 */
- .error-boundary {
- display: flex;
- flex-direction: column;
- justify-content: center;
- align-items: center;
- height: 100vh;
- text-align: center;
- padding: 20px;
-
- h2 {
- color: #f56c6c;
- margin-bottom: 20px;
- }
-
- button {
- margin-top: 20px;
- padding: 10px 20px;
- background-color: #409eff;
- color: white;
- border: none;
- border-radius: 4px;
- cursor: pointer;
- }
- }
- #app {
- min-height: 100vh;
- background-color: var(--bg-color);
- color: var(--text-color);
- }
-
- /* 确保菜单不被其他元素覆盖 */
- .custom-tabbar {
- z-index: 99999 !important;
- position: fixed !important;
- bottom: 0 !important;
- left: 0 !important;
- right: 0 !important;
- }
-
- /* 修复页面内容被遮挡的问题 */
- .page-content {
- padding-bottom: 140rpx !important;
- }
-
- /* 确保tabbar显示 */
- uni-tabbar {
- display: flex !important;
- position: fixed;
- bottom: 0;
- left: 0;
- right: 0;
- z-index: 9999;
- background-color: #fff;
- box-shadow: 0 -2px 10px rgba(0,0,0,0.1);
- }
-
- /* 修复高度问题 */
- uni-tabbar .uni-tabbar {
- height: 50px !important;
- }
-
- /* 页面内容区域 */
- .page-content {
- padding-bottom: 60px !important;
- }
-
- .app-header {
- background: var(--header-bg, #2a5caa);
- padding: 10px;
- display: flex;
- justify-content: space-around;
- position: sticky;
- top: 0;
- z-index: 1000;
-
- a {
- color: white;
- text-decoration: none;
- font-weight: bold;
-
- &.router-link-exact-active {
- color: #ffcc00;
- border-bottom: 2px solid #ffcc00;
- }
- }
- }
- </style>
|