本文最后更新于 69 天前,其中的信息可能已经有所发展或是发生改变。
🌟 为什么要选择Vue3?
+ 性能提升:虚拟DOM重写,速度提升2倍+
+ 体积优化:Tree-shaking支持,核心包仅11kb
+ 组合式API:更好的逻辑复用与TypeScript支持
+ 响应式升级:基于Proxy实现全语言特性支持
⚡ 5分钟环境搭建
1. 使用Vite创建项目
npm create vue@latest
✔ Project name: vue3-demo
✔ Add TypeScript? Yes
✔ Add Pinia? Yes
✔ Add Vue Router? Yes
✔ Add ESLint? Yes
2. 目录结构解析
src/
├── main.ts # 应用入口
├── App.vue # 根组件
├── views/ # 页面组件
├── components/ # 通用组件
├── router/ # 路由配置
├── stores/ # Pinia状态管理
└── assets/ # 静态资源
3. 开发命令
npm run dev # 启动开发服务器
npm run build # 生产环境构建
💡 核心语法速览
1. 组合式API基础
<script setup>
import { ref, computed } from 'vue'
// 响应式数据
const count = ref(0)
// 计算属性
const double = computed(() => count.value * 2)
// 方法
const increment = () => count.value++
</script>
<template>
<button @click="increment">
{{ count }} → {{ double }}
</button>
</template>
2. 响应式对象
const user = reactive({
name: 'Alice',
age: 25,
skills: ['Vue', 'TypeScript']
})
// 自动追踪依赖
watchEffect(() => {
console.log(`用户名更新为:${user.name}`)
})
🔥 六大必会特性
特性1:组件通信
<!-- 父组件 -->
<Child :msg="message" @update="handleUpdate" />
<!-- 子组件 -->
<script setup>
defineProps(['msg'])
defineEmits(['update'])
</script>
特性2:Fragment组件
<template>
<header>导航栏</header>
<main>内容区</main>
<footer>底部信息</footer>
</template>
特性3:Teleport传送门
<teleport to="#modal-container">
<div class="modal">
<slot />
</div>
</teleport>
🛠️ 企业级实战方案
1. 全局状态管理(Pinia)
// stores/counter.js
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
actions: {
increment() { this.count++ }
}
})
// 组件中使用
const counter = useCounterStore()
2. 路由配置(Vue Router)
// router/index.ts
const routes = [
{
path: '/',
component: HomeView,
meta: { requiresAuth: true }
},
{
path: '/login',
component: () => import('@/views/LoginView.vue')
}
]
3. 异步组件加载
<script setup>
const AsyncComponent = defineAsyncComponent(() =>
import('./components/HeavyComponent.vue')
)
</script>
🚀 性能优化策略
优化方向 | 实现方法 | 效果提升 |
---|---|---|
代码分割 | 路由级组件动态导入 | 首屏加载快60% |
响应式优化 | 使用shallowRef/shallowReactive | 内存消耗降40% |
列表渲染 | v-for搭配key属性 | 更新速度提升3x |
静态提升 | 编译器自动优化 | Patch速度提升2x |
⚠️ 常见问题指南
1. 响应式丢失问题
// ❌ 错误写法
const { x, y } = reactivePos
// ✅ 正确写法
const pos = reactive({ x: 0, y: 0 })
const x = toRef(pos, 'x')
const y = toRef(pos, 'y')
2. 生命周期对比
Vue2选项式API Vue3组合式API
beforeCreate → setup()
created → setup()
beforeMount → onBeforeMount
mounted → onMounted
beforeUpdate → onBeforeUpdate
updated → onUpdated
beforeUnmount → onBeforeUnmount
unmounted → onUnmounted
3. TypeScript支持
interface User {
id: number
name: string
}
const user = reactive<User>({ id: 1, name: 'John' })
+ 官方推荐学习路径:Vue3 → Pinia → Vue Router → Vite
+ 最新特性:尝试 Composition API + <script setup> 语法
- 注意:避免在reactive中使用解构操作
写的不错,对新手用户十分友好,易懂,继续加油!!!