Vue3 是目前最主流的渐进式前端框架之一。本文从零开始,带你理解 组合式 API(Composition API)、响应式系统 与 组件通信,并动手搭建一个真实的小项目。

一、环境准备

首先确认 Node.js 版本 ≥ 18,然后使用 Vite 快速创建项目:

bash
# 使用 Vite 创建 Vue3 + JavaScript 项目
npm create vite@latest my-vue-app -- --template vue
cd my-vue-app
npm install
npm run dev   # 启动开发服务器 http://localhost:5173

二、组合式 API 基础

Vue3 推荐使用 setup 语法糖 <script setup>,用 ref 声明响应式数据,用 computed 派生计算属性:

vue
<!-- Counter.vue -->
<script setup>
import { ref, computed } from 'vue'

const count = ref(0)
const doubled = computed(() => count.value * 2)

function increment() { count.value++ }
</script>

<template>
  <button @click="increment">{{ count }} / {{ doubled }}</button>
</template>

三、组件通信

父组件通过 props 传值给子组件,子组件通过 emit 触发事件通知父组件:

vue
<!-- 子组件 Child.vue -->
<script setup>
const props = defineProps({ title: String })
const emit = defineEmits(['select'])
</script>

<template>
  <button @click="emit('select', props.title)">{{ props.title }}</button>
</template>
提示:组件通信优先用 props/emit;跨层级复杂状态可引入 Pinia 统一管理,避免深层嵌套传递。

四、小结与下一步

通过本文你已掌握 Vue3 的核心概念。下一步可以尝试:组合式函数的封装复用、Vue Router 路由、Pinia 状态管理,以及用 Vite 构建生产包并部署。