一文帶你從零開始搭建vue3項目
說明
記錄一次Vue3的項目搭建過程。文章基于 vue3.2.6 和 vite2.51 版本,使用了ui庫 Element plus,vue-router4,Layout布局封裝,axios請求封裝,別名配置等。
開始
1. 使用 vscode 開發(fā)工具安裝vue3的插件 Volar ,在vue2中我們使用的是Vetur。
- vue3在線code工具 傳送門sfc.vuejs.org/
2. 執(zhí)行初始化及安裝命令:
npm init vite 初始化vite此過程可以輸入項目名、選擇vue/react項目及js/ts環(huán)境選擇,vue3已經(jīng)完全支持ts,此文章使用的是js。npm install 安裝依賴。最后執(zhí)行npm run dev運行項目。

運行過程時如果出現(xiàn)上圖的報錯信息,可以手動執(zhí)行 node node_modules/esbuild/install.js,然后再執(zhí)行npm run dev
3. 安裝vue-router
執(zhí)行 npm install vue-router@4 , vue3對應的vue-router和vuex的版本都是 4.0。執(zhí)行命令安裝完成之后,在目錄下創(chuàng)建 src/router/index.js 寫入下面的配置:
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
// ...
]
export default createRouter({
history: createWebHistory(),
routes,
})
main.js中使用
// ...+
import router from './router/index'
createApp(App).use(router).mount('#app')
vue-router4寫法和以前的有些區(qū)別 hash模式 createWebHashHistory history模式 createWebHistory,具體可查看官網(wǎng)。
4. 全局樣式及sass安裝(使用@路徑需要配置別名,后文有相應的說明)
執(zhí)行命令npm i sass -D,然后在目錄下創(chuàng)建 src/styles/index.scss:
// @import './a.scss'; // 作為出口組織這些樣式文件,同時編寫一些全局樣式
在 mian.js 中引入
import '@/styles/index.scss'
tips: vue3中樣式穿透 使用::deep(.className) 或者 deep(.className)
5. Element plus按需引入和全局引入
執(zhí)行npm i element3 -S命令安裝,如果你能用到里面的大多數(shù)組件,就用全局引入方式,如下:
// main.js
import element3 from "element3";
import "element3/lib/theme-chalk/index.css";
createApp(App).use(router).use(element3).mount('#app')
如果你只用到幾個組件,就可以按需加載優(yōu)化性能,創(chuàng)建src/plugins/element3.js,如下
// 按需引入 plugins/element3.js
import { ElButton, ElMenu, ElMenuItem } from 'element3'
import 'element3/lib/theme-chalk/button.css'
import 'element3/lib/theme-chalk/menu.css'
import 'element3/lib/theme-chalk/menu-item.css'
export default function (app) {
app.use(ElButton)
app.use(ElMenu)
app.use(ElMenuItem)
}
// main.js中引用
import element3 from '@/plugins/element3.js'
createApp(App).use(router).use(element3).mount('#app')
6. Layout布局,創(chuàng)建文件src/layout/index.vue
// src/layout/index.vue <template> <!-- 頂部導航 --> <Navbar /> <!-- 頁面內(nèi)容部分、路由出口 --> <AppMain /> <!-- 底部內(nèi)容 --> <Footer /> </template> <script setup> import Navbar from './Navbar.vue' import AppMain from './AppMain.vue' import Footer from './Footer.vue' </script>
根據(jù)自己的需求設(shè)計布局,使用Layout布局時,需要注意將Layout.vue作為父路由,路由設(shè)計大概像下面這樣:
// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/layout/index.vue'
import Home from '@/views/home/Home.vue'
import Test from '@/views/test/Test.vue'
const routes = [
{
path: '/',
component: Layout,
children: [{ path: '', component: Home }],
},
{
path: '/test',
component: Layout,
children: [{ path: '', component: Test }],
},
]
export default createRouter({
history: createWebHistory(),
routes,
})
7. axios請求封裝
執(zhí)行命令 npm i axios 安裝axios
新建 src/utils/request.js,在此文件中進行封裝axios
import axios from 'axios'
// 可以導入element plus 的彈出框代替alert進行交互操作
// create an axios instance
const service = axios.create({
baseURL: import.meta.env.VITE_APP_BASEURL, // 使用設(shè)置好的全局環(huán)境
timeout: 30 * 1000, // request timeout
})
// request interceptor
service.interceptors.request.use(
(config) => {
// 此處可以執(zhí)行處理添加token等邏輯
// config.headers["Authorization"] = getToken();
return config
},
(error) => {
console.log(error)
return Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(
(response) => {
const res = response.data // 根據(jù)接口返回參數(shù)自行處理
if (res.code !== 200) {
if (res.code === 50000) {
// 根據(jù)狀態(tài)碼自行處理
alert('服務(wù)器內(nèi)部出現(xiàn)異常,請稍后再試')
}
return Promise.reject(new Error(res.msg || 'Error'))
} else {
// 調(diào)用成功返回數(shù)據(jù)
return Promise.resolve(res)
}
},
(error) => {
console.log('err' + error) // 出現(xiàn)異常的處理
return Promise.reject(error)
}
)
export default service
新建 src/api 目錄,可以每個模塊或每個頁面單獨建立一個js文件,方便管理維護api。此處示例,新建 src/api/home.js 文件,寫入代碼
// 引入封裝好的 request.js
import request from '@/utils/request'
export function getList(query) {
return request({
url: '/list',
method: 'get',
params: query,
})
}
在 home.vue 中使用
<script setup>
import { getList } from '@/api/home.js'
const query = { pagenum: 1 }
getList(query)
.then((res) => {
console.log(res) // 調(diào)用成功返回的數(shù)據(jù)
})
.error((err) => {
console.log(err) // 調(diào)用失敗要執(zhí)行的邏輯
})
</script>
8. 環(huán)境變量相關(guān)
項目根目錄下創(chuàng)建三個文件.env.production 生產(chǎn)環(huán)境 .env.development 開發(fā)環(huán)境 .env.staging 測試環(huán)境 ,分別加入下面的代碼,在不同的編譯環(huán)境下,打包時自動執(zhí)行當前環(huán)境下的代碼
# .env.production VITE_APP_BASEURL=https://www.prod.api/
# .env.development VITE_APP_BASEURL=https://www.test.api/
# .env.staging VITE_APP_BASEURL=https://www.test.api/
使用:
console.log(import.meta.env.VITE_APP_BASEURL) // 在不同編譯環(huán)境下控制臺會輸出不同的url路徑
在package.json中通過傳遞 --mode 選項標志來覆蓋命令使用的默認模式
"scripts": {
"dev": "vite",
"build:stage": "vite build --mode staging",
"build:prod": "vite build --mode production",
"serve": "vite preview"
},
這樣,生產(chǎn)環(huán)境打包執(zhí)行npm run build:prod,測試/預發(fā)布環(huán)境打包npm run build:stage
9. vite中別名配置
根目錄下 vite.config.js 文件添加代碼
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: [{ find: '@', replacement: resolve(__dirname, 'src') }],
},
base: './',
})
總結(jié)
到此這篇關(guān)于從零開始搭建vue3項目的文章就介紹到這了,更多相關(guān)vue3項目搭建內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Vue中Class和Style實現(xiàn)v-bind綁定的幾種用法
項目開發(fā)中給元素添加/刪除 class 是非常常見的行為之一, 例如網(wǎng)站導航都會給選中項添加一個 active 類用來區(qū)別選與未選中的樣式,那么在 vue 中 我們?nèi)绾翁幚磉@類的效果呢?下面我們就一起來了解一下2021-05-05
vue部署到線上為啥會出現(xiàn)404的原因分析及解決
這篇文章主要介紹了vue部署到線上為啥會出現(xiàn)404的原因分析及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04
Vue調(diào)試工具vue-devtools的安裝與使用
vue-devtools是專門調(diào)試vue項目的調(diào)試工具,安裝成功之后,右邊會出現(xiàn)一個vue,就可以在線可以調(diào)試vue了,下面這篇文章主要給大家介紹了關(guān)于Vue調(diào)試工具vue-devtools的安裝與使用的相關(guān)資料,需要的朋友可以參考下2022-07-07
解決vue更新路由router-view復用組件內(nèi)容不刷新的問題
今天小編就為大家分享一篇解決vue更新路由router-view復用組件內(nèi)容不刷新的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-11-11
Element-Plus實現(xiàn)動態(tài)渲染圖標的示例代碼
在Element-Plus中,我們可以使用component標簽來動態(tài)渲染組件,本文主要介紹了Element-Plus?實現(xiàn)動態(tài)渲染圖標教程,具有一定的參考價值,感興趣的可以了解一下2024-03-03

