Vue 3 入门
Vue 3 是目前最流行的前端框架之一,由尤雨溪主导开发,以渐进式、响应式、组件化为核心理念。相比 Vue 2,Vue 3 引入了 Composition API、<script setup> 语法糖、Proxy 响应式系统和更好的 TypeScript 支持,性能提升约 50%。
MVVM 与 Vue 的定位
Vue 采用 MVVM(Model-View-ViewModel) 模式:
| 层 | 对应 | 说明 |
|---|---|---|
| Model | ref/reactive 数据 | 应用的状态 |
| View | <template> 模板 | 用户看到的 DOM |
| ViewModel | Vue 运行时 | 自动同步 Model ↔ View |
开发者只需声明数据和逻辑,Vue 自动把数据变化反映到 DOM,无需手动操作 DOM(不再需要 document.querySelector 或 jQuery)。
快速开始
方式一:CDN 引入(无需构建,适合快速验证)
<!DOCTYPE html>
<html>
<head><title>Vue 3 Demo</title></head>
<body>
<div id="app">{{ message }}</div>
<script type="module">
import { createApp, ref } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js'
createApp({
setup() {
const message = ref('Hello, Vue 3!')
return { message }
}
}).mount('#app')
</script>
</body>
</html>方式二:Vite 项目(推荐,生产环境使用)
# 创建项目(交互式引导)
npm create vue@latest
# 进入目录并启动
cd <project-name>
npm install
npm run devnpm create vue@latest 是 Vue 官方脚手架(基于 Vite),会引导你选择 TypeScript、Router、Pinia、ESLint 等功能。
创建应用:createApp
每个 Vue 应用从 createApp() 开始,传入一个根组件:
// src/main.ts
import { createApp } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
const app = createApp(App) // 创建应用实例
app.use(createPinia()) // 注册插件
app.use(router)
app.mount('#app') // 挂载到 index.html 中 id="app" 的元素
mount() 之后 Vue 才开始渲染,所有插件必须在 mount 之前注册。
单文件组件(SFC)
Vue 的核心开发单元是 .vue 文件(Single File Component),一个文件包含完整的 HTML 结构、脚本和样式:
<!-- src/components/HelloWorld.vue -->
<script setup lang="ts">
import { ref } from 'vue'
// defineProps 声明外部传入的属性
const props = defineProps<{ name: string }>()
// ref 创建响应式数据
const count = ref(0)
</script>
<template>
<div class="hello">
<h2>你好,{{ props.name }}!</h2>
<p>点击次数:{{ count }}</p>
<button @click="count++">点击 +1</button>
</div>
</template>
<style scoped>
/* scoped 使样式只作用于本组件 */
.hello {
padding: 1rem;
border: 1px solid #ddd;
border-radius: 8px;
}
</style>在父组件中使用:
<script setup>
import HelloWorld from '@/components/HelloWorld.vue'
</script>
<template>
<HelloWorld name="Vue 3" />
</template>Options API vs Composition API
Vue 3 同时支持两种 API 风格,新项目推荐使用 Composition API + <script setup>。
<script setup>
import { ref, computed, onMounted } from 'vue'
const count = ref(0)
const double = computed(() => count.value * 2)
function increment() {
count.value++
}
onMounted(() => {
console.log('组件已挂载')
})
</script>
<template>
<button @click="increment">{{ count }}(×2 = {{ double }})</button>
</template>| 对比维度 | Options API | Composition API |
|---|---|---|
| 代码组织 | 按选项(data/methods/computed)分散 | 按功能聚合,逻辑集中 |
| 逻辑复用 | Mixin(易冲突) | Composable 函数(清晰) |
| TypeScript | 类型推断有限 | 完整类型支持 |
| 适用场景 | 简单组件、迁移项目 | 新项目首选 |
响应式基础
Vue 3 的响应式基于 ES6 Proxy,与 Vue 2 的 Object.defineProperty 相比支持更多数据类型。
<script setup>
import { ref, reactive } from 'vue'
// ref:包装任意类型(JS 中用 .value,模板中自动解包)
const count = ref(0)
const name = ref('Alice')
count.value++ // JS 中必须 .value
// {{ count }} 模板中无需 .value
// reactive:包装对象(JS 中直接访问属性,无需 .value)
const state = reactive({
user: { name: 'Bob', age: 25 },
list: [1, 2, 3],
})
state.user.name = 'Charlie' // 直接修改属性
state.list.push(4)
</script>常见错误:解构 reactive 对象后会失去响应性。
const { name } = state // ❌ name 不再是响应式的
正确做法:使用 toRefs() 或直接访问 state.name。
应用配置
const app = createApp(App)
// 注册全局组件
app.component('MyIcon', MyIconComponent)
// 注册全局指令
app.directive('focus', {
mounted(el) { el.focus() }
})
// 全局错误处理
app.config.errorHandler = (err, instance, info) => {
console.error('Vue Error:', err, info)
}
app.mount('#app')最后更新于