Vue.js 是一個流行的前端框架,它的最新版本 Vue 3 帶來了許多新特性和改進。本文將詳細介紹如何從零開始搭建一個 Vue 3 項目,涵蓋從環境準備到項目部署的完整流程。無論你是初學者還是有一定經驗的開發者,本文都將為你提供詳細的指導和實用的技巧。
在開始之前,確保你的系統已經安裝了 Node.js。Node.js 是一個基于 Chrome V8 引擎的 JavaScript 運行時,它允許你在服務器端運行 JavaScript 代碼。
node -v
npm -v
如果顯示了版本號,說明安裝成功。
Vue CLI 是 Vue.js 官方提供的命令行工具,用于快速搭建 Vue 項目。
npm install -g @vue/cli
vue --version
如果顯示了版本號,說明安裝成功。
vue create my-vue3-project
在提示中選擇 Manually select features
,然后選擇以下特性:
選擇 Vue 3 版本。
選擇 ESLint + Prettier
作為代碼風格檢查工具。
選擇 In dedicated config files
將配置放在單獨的文件中。
選擇 Save this as a preset for future projects
保存配置,方便下次使用。
創建完成后,項目結構如下:
my-vue3-project/
├── node_modules/
├── public/
│ ├── favicon.ico
│ └── index.html
├── src/
│ ├── assets/
│ ├── components/
│ ├── router/
│ ├── store/
│ ├── views/
│ ├── App.vue
│ └── main.ts
├── .eslintrc.js
├── .prettierrc
├── babel.config.js
├── package.json
├── tsconfig.json
└── vue.config.js
node_modules/
:存放項目依賴的第三方庫。public/
:存放靜態資源,如 index.html
。src/
:存放項目源代碼。
assets/
:存放靜態資源,如圖片、字體等。components/
:存放 Vue 組件。router/
:存放路由配置。store/
:存放 Vuex 狀態管理配置。views/
:存放頁面組件。App.vue
:根組件。main.ts
:項目入口文件。.eslintrc.js
:ESLint 配置文件。.prettierrc
:Prettier 配置文件。babel.config.js
:Babel 配置文件。package.json
:項目配置文件,包含項目依賴和腳本。tsconfig.json
:TypeScript 配置文件。vue.config.js
:Vue 項目配置文件。ESLint 是一個 JavaScript 代碼檢查工具,用于發現和修復代碼中的問題。
.eslintrc.js
文件,配置如下: module.exports = {
root: true,
env: {
node: true,
},
extends: [
'plugin:vue/vue3-essential',
'eslint:recommended',
'@vue/typescript/recommended',
'@vue/prettier',
'@vue/prettier/@typescript-eslint',
],
parserOptions: {
ecmaVersion: 2020,
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
},
};
package.json
中添加以下腳本: "scripts": {
"lint": "eslint --ext .js,.vue src"
}
npm run lint
Prettier 是一個代碼格式化工具,用于統一代碼風格。
.prettierrc
文件,配置如下: {
"semi": true,
"singleQuote": true,
"trailingComma": "es5",
"printWidth": 80,
"tabWidth": 2
}
package.json
中添加以下腳本: "scripts": {
"format": "prettier --write \"src/**/*.{js,vue,ts}\""
}
npm run format
TypeScript 是 JavaScript 的超集,提供了類型檢查和更強大的面向對象編程特性。
tsconfig.json
文件,配置如下: {
"compilerOptions": {
"target": "esnext",
"module": "esnext",
"strict": true,
"jsx": "preserve",
"importHelpers": true,
"moduleResolution": "node",
"experimentalDecorators": true,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"sourceMap": true,
"baseUrl": ".",
"types": ["webpack-env"],
"paths": {
"@/*": ["src/*"]
},
"lib": ["esnext", "dom", "dom.iterable", "scripthost"]
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue", "tests/**/*.ts", "tests/**/*.tsx"],
"exclude": ["node_modules"]
}
src
目錄下創建 shims-vue.d.ts
文件,配置如下: declare module '*.vue' {
import { DefineComponent } from 'vue';
const component: DefineComponent<{}, {}, any>;
export default component;
}
Vue Router 是 Vue.js 的官方路由管理器,用于構建單頁面應用。
npm install vue-router@4
src/router/index.ts
文件,配置如下: import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import Home from '../views/Home.vue';
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Home',
component: Home,
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue'),
},
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes,
});
export default router;
src/main.ts
文件中引入并使用路由: import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
createApp(App).use(router).mount('#app');
src/App.vue
文件中添加 <router-view>
標簽: <template>
<div id="app">
<router-view />
</div>
</template>
Vuex 是 Vue.js 的官方狀態管理庫,用于集中管理應用的狀態。
npm install vuex@next
src/store/index.ts
文件,配置如下: import { createStore } from 'vuex';
export default createStore({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
},
},
actions: {
increment({ commit }) {
commit('increment');
},
},
modules: {},
});
src/main.ts
文件中引入并使用 Vuex: import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
createApp(App).use(router).use(store).mount('#app');
src/views/Home.vue
文件中使用 Vuex: <template>
<div class="home">
<h1>Count: {{ count }}</h1>
<button @click="increment">Increment</button>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { mapState, mapActions } from 'vuex';
export default defineComponent({
computed: {
...mapState(['count']),
},
methods: {
...mapActions(['increment']),
},
});
</script>
Element Plus 是一個基于 Vue 3 的 UI 組件庫,提供了豐富的組件和樣式。
npm install element-plus
src/main.ts
文件中引入并使用 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/lib/theme-chalk/index.css';
createApp(App).use(router).use(store).use(ElementPlus).mount('#app');
src/views/Home.vue
文件中使用 Element Plus 組件: <template>
<div class="home">
<el-button type="primary" @click="increment">Increment</el-button>
<h1>Count: {{ count }}</h1>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
import { mapState, mapActions } from 'vuex';
export default defineComponent({
computed: {
...mapState(['count']),
},
methods: {
...mapActions(['increment']),
},
});
</script>
Axios 是一個基于 Promise 的 HTTP 客戶端,用于發送 HTTP 請求。
npm install axios
src
目錄下創建 api
文件夾,并在其中創建 index.ts
文件: import axios from 'axios';
const api = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 1000,
});
export default api;
src/views/Home.vue
文件中使用 Axios 發送請求: <template>
<div class="home">
<el-button type="primary" @click="fetchData">Fetch Data</el-button>
<ul>
<li v-for="post in posts" :key="post.id">{{ post.title }}</li>
</ul>
</div>
</template>
<script lang="ts">
import { defineComponent, ref } from 'vue';
import api from '../api';
export default defineComponent({
setup() {
const posts = ref([]);
const fetchData = async () => {
const response = await api.get('/posts');
posts.value = response.data;
};
return {
posts,
fetchData,
};
},
});
</script>
代碼分割是一種優化技術,用于將代碼拆分成多個小塊,按需加載,減少初始加載時間。
src/router/index.ts
文件中使用動態導入實現代碼分割: const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Home',
component: () => import('../views/Home.vue'),
},
{
path: '/about',
name: 'About',
component: () => import('../views/About.vue'),
},
];
懶加載是一種優化技術,用于延遲加載非關鍵資源,提高頁面加載速度。
src/views/About.vue
文件中使用懶加載: <template>
<div class="about">
<h1>This is an about page</h1>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
name: 'About',
});
</script>
v-if
和 v-show
控制組件的渲染和顯示。keep-alive
緩存組件狀態。v-once
渲染靜態內容。v-memo
優化列表渲染。 npm run build
dist
目錄下。dist
目錄下的文件上傳到服務器。index.html
文件。本文詳細介紹了如何從零開始搭建一個 Vue 3 項目,涵蓋了環境準備、項目創建、配置、路由、狀態管理、UI框架集成、API請求、項目優化和部署等各個方面。通過本文的指導,你應該能夠順利搭建并部署一個 Vue 3 項目。希望本文對你有所幫助,祝你在 Vue 3 的開發之旅中取得成功!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。