Vue.js 应用启动入口文件:配置路由、状态管理、全局 Axios 和 Element Plus

import { createApp } from 'vue'
import '@/assets/css/reset.css'
import 'element-plus/dist/index.css'
import App from './App.vue'
import router from './router'
import store from './store'
import { globalAxios } from './request'
import 'video.js/dist/video-js.css' //videojs样式


// 引入element-plus
// import { setupElementPlus } from '@/plugins/elementPlus'

import * as ElementPlusIconsVue from '@element-plus/icons-vue'

// 使用antd

// 创建实例
const setupAll = async () => {
    const app = createApp(App)

    // 使用全局axios
    app.use(globalAxios)

    // 使用vuex
    app.use(store)

    // 使用路由
    app.use(router)

    // setupElementPlus(app)

    for (const name in ElementPlusIconsVue) {
        app.component(name, (ElementPlusIconsVue as any)[name])
    }

    router.beforeEach((to) => {
        if (to.meta) {
            to.meta.notPrefix ? (document.title = to.meta.title) : (window.document.title = '隧道信息化平台' + (to.meta.title ? '-' + to.meta.title : ''))
        }
    })

    router.isReady().then(() => {
        app.mount('#app')
    }).catch((error) => {
        console.error('An error occurred while preparing the router:', error)
    })
}

setupAll()

代码解析:

  1. 引入必要的模块:

    • createApp 用于创建 Vue 应用实例。
    • App.vue 是主组件。
    • router 是路由配置。
    • store 是状态管理配置。
    • globalAxios 是全局 Axios 实例。
    • element-plus/dist/index.css 是 Element Plus 的样式文件。
    • video.js/dist/video-js.css 是 video.js 的样式文件。
  2. 注册 Element Plus 图标:

    • 使用 ElementPlusIconsVue 注册 Element Plus 图标组件。
  3. 创建应用实例:

    • 使用 createApp(App) 创建 Vue 应用实例。
  4. 使用全局 Axios、Vuex 和路由:

    • app.use(globalAxios) 使用全局 Axios。
    • app.use(store) 使用 Vuex 状态管理。
    • app.use(router) 使用路由。
  5. 设置页面标题:

    • router.beforeEach 钩子函数用于在路由切换前设置页面标题。
  6. 挂载应用:

    • router.isReady().then(() => app.mount('#app')) 在路由准备就绪后将应用挂载到 #app 元素上。

错误处理:

  • 代码中使用了 router.isReady().then() 方法,这是一个异步方法,用于确保路由准备就绪后再执行后续操作。
  • 为了避免在准备就绪期间发生错误导致应用程序无法挂载,在 then() 方法中添加了 catch 块用于处理错误。
  • 如果发生错误,错误信息会输出到控制台,并阻止应用程序继续执行。

最佳实践:

  • 使用 catch 块处理异步操作中的错误,提高应用程序的健壮性。
  • 确保错误信息输出到控制台,以便于调试和解决问题。
  • 考虑使用错误监控工具,以便及时了解应用程序中的错误。
Vue.js 应用启动入口文件:配置路由、状态管理、全局 Axios 和 Element Plus

原文地址: https://www.cveoy.top/t/topic/pkdZ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录