艺术图片主要是吸引各位的注意力啊
创建一个基于 Vite 和 Vue 3 的现代 Web 应用通常包括设置项目结构、配置路由、状态管理、API 请求处理以及整合 UI 框架。下面我会为你详细介绍如何从零开始构建一个以 Vue 3 为基础,使用 Element Plus 作为 UI 框架的项目。
一、创建项目
-
创建一个基于 Vite 的 Vue 项目
npm create vite@latest my-project -- --template vue
这条命令将会创建一个名为
my-project
的新项目,并使用 Vue 为模板。 -
进入项目目录:
cd my-project
安装依赖:
npm install
二、项目结构初始化
-
进入
src
目录,准备创建必要的文件夹:cd src
创建基础目录:路由 (
router
)、状态管理 (store
)、API 请求 (axios
)、页面 (views
)、配置文件 (config
):mkdir router store axios views config cd ..
修改
App.vue
,设置为基本的路由视图:<template> <router-view /> </template> <style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
三、路由配置
-
安装 Vue Router:
npm install vue-router@4
在
router
目录下创建index.js
文件 并配置基本路由:import { createRouter, createWebHashHistory } from "vue-router"; const routes = [ { path: "/", name: "home", component: () => import("../views/Home.vue") }, ]; const router = createRouter({ history: createWebHashHistory(), routes, }); export default router;
在views目录下创建index.vue文件并写入如下代码
<template> <button @click="countAdd">Count is: {{ count }}</button> </template> <script setup> import { reactive, toRefs } from "vue"; import store from "@/store"; const state = reactive({ count: store.state.count, }); const { count } = toRefs(state); const countAdd = () => { // 获取存储的count以及给值加1 store.commit("set", ["count", store.state.count + 1]); // 修改页面count显示的值为新存储的值 state.count = store.state.count; } </script> <style scoped> button { font-weight: bold; } </style>
四、状态管理配置(使用 Vuex 4)
-
安装 Vuex:
npm install vuex@next --save
在
store
目录下创建index.js
:import { createStore } from "vuex"; const store = createStore({ state() { return { count: 0 }; }, mutations: { increment(state) { state.count++; } } }); export default store;
五、配置 Axios
-
安装 Axios
npm install axios
在
axios
目录下创建index.js
设置基本的 Axios 实例和拦截器:import axios from "axios"; const instance = axios.create({ baseURL: 'https://api.example.com', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} }); export default instance;
六、集成 Element Plus UI 框架
-
安装 Element Plus 及其图标库:
npm install element-plus npm install @element-plus/icons-vue
在
main.js
中引入 Element Plus 并全局注册:import { createApp } from 'vue'; import App from './App.vue'; import router from './router'; import store from './store'; import ElementPlus from 'element-plus'; import 'element-plus/dist/index.css'; const app = createApp(App); app.use(ElementPlus); app.use(store); app.use(router); app.mount('#app');