Vue 3 基本教程 - 運行一個最小 Demo
1. 創建項目
使用 Vue 官方腳手架工具創建一個新項目:
# 安裝 Vue CLI (如果尚未安裝)
npm install -g @vue/cli# 創建一個新項目
vue create vue3-demo# 選擇 Vue 3 預設
# 使用方向鍵選擇 "Default (Vue 3)" 然后按 Enter
或者使用 Vite(更快的開發工具):
# 使用 Vite 創建項目
npm create vite@latest vue3-demo -- --template vue# 進入項目目錄
cd vue3-demo
2. 項目結構
基本項目結構如下:
vue3-demo/
├── node_modules/
├── public/
├── src/
│ ├── assets/
│ ├── components/
│ ├── App.vue # 主組件
│ └── main.js # 入口文件
├── package.json
└── vite.config.js (或 vue.config.js)
3. 修改 App.vue
打開 src/App.vue
文件,將其修改為一個簡單的計數器應用:
<template><div class="container"><h1>Vue 3 最小 Demo</h1><p>當前計數: {{ count }}</p><button @click="increment">增加</button><button @click="decrement">減少</button></div>
</template><script setup>
import { ref } from 'vue'// 使用 ref 創建響應式狀態
const count = ref(0)// 方法
function increment() {count.value++
}function decrement() {count.value--
}
</script><style scoped>
.container {max-width: 400px;margin: 0 auto;padding: 20px;text-align: center;font-family: Arial, sans-serif;
}button {margin: 0 5px;padding: 8px 16px;background-color: #4CAF50;color: white;border: none;border-radius: 4px;cursor: pointer;
}button:hover {background-color: #45a049;
}
</style>
4. 運行項目
安裝依賴并啟動開發服務器:
# 安裝依賴
npm install# 啟動開發服務器
npm run dev
啟動后,在瀏覽器中打開顯示的地址(通常是 http://localhost:5173 或 http://localhost:8080)
5. 代碼解釋
- script setup: Vue 3 的 Composition API 語法糖,簡化了組件的編寫
- ref(0): 創建一個值為 0 的響應式引用,當它變化時會自動更新視圖
- count.value: 訪問或修改 ref 的值需要使用 .value 屬性
- @click: Vue 的事件綁定語法,點擊按鈕時調用對應的方法
- {{ count }}: 模板中的插值表達式,顯示響應式變量的值
6. 添加一個新組件
創建 src/components/HelloWorld.vue
文件:
<template><div class="hello"><h2>{{ msg }}</h2></div>
</template><script setup>
defineProps({msg: {type: String,required: true}
})
</script><style scoped>
.hello {background-color: #f5f5f5;padding: 10px;border-radius: 5px;margin-top: 20px;
}
</style>
修改 App.vue
以使用新組件:
<template><div class="container"><h1>Vue 3 最小 Demo</h1><p>當前計數: {{ count }}</p><button @click="increment">增加</button><button @click="decrement">減少</button><HelloWorld msg="這是一個子組件" /></div>
</template><script setup>
import { ref } from 'vue'
import HelloWorld from './components/HelloWorld.vue'// 使用 ref 創建響應式狀態
const count = ref(0)// 方法
function increment() {count.value++
}function decrement() {count.value--
}
</script><!-- 樣式部分保持不變 -->
7. 總結
這個最小 Demo 展示了 Vue 3 的基本功能:
- 響應式狀態管理(使用 ref)
- 事件處理
- 組件創建和使用
- prop 傳遞
Vue 3 的 Composition API 和 script setup 語法使代碼更簡潔、更易于組織和重用。