Vue.js 应用启动入口文件:配置路由、状态管理、全局 Axios 和 Element Plus
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()
代码解析:
-
引入必要的模块:
createApp用于创建 Vue 应用实例。App.vue是主组件。router是路由配置。store是状态管理配置。globalAxios是全局 Axios 实例。element-plus/dist/index.css是 Element Plus 的样式文件。video.js/dist/video-js.css是 video.js 的样式文件。
-
注册 Element Plus 图标:
- 使用
ElementPlusIconsVue注册 Element Plus 图标组件。
- 使用
-
创建应用实例:
- 使用
createApp(App)创建 Vue 应用实例。
- 使用
-
使用全局 Axios、Vuex 和路由:
app.use(globalAxios)使用全局 Axios。app.use(store)使用 Vuex 状态管理。app.use(router)使用路由。
-
设置页面标题:
router.beforeEach钩子函数用于在路由切换前设置页面标题。
-
挂载应用:
router.isReady().then(() => app.mount('#app'))在路由准备就绪后将应用挂载到#app元素上。
错误处理:
- 代码中使用了
router.isReady().then()方法,这是一个异步方法,用于确保路由准备就绪后再执行后续操作。 - 为了避免在准备就绪期间发生错误导致应用程序无法挂载,在
then()方法中添加了catch块用于处理错误。 - 如果发生错误,错误信息会输出到控制台,并阻止应用程序继续执行。
最佳实践:
- 使用
catch块处理异步操作中的错误,提高应用程序的健壮性。 - 确保错误信息输出到控制台,以便于调试和解决问题。
- 考虑使用错误监控工具,以便及时了解应用程序中的错误。
原文地址: https://www.cveoy.top/t/topic/pkdZ 著作权归作者所有。请勿转载和采集!