简介:本文系统梳理Vue3核心语法体系,涵盖响应式原理、组合式API、模板语法等核心模块,通过20+代码示例与3个完整案例,帮助开发者快速掌握Vue3开发范式,提升前端工程化能力。
Vue3作为Vue.js的第三代框架,在保持渐进式框架特性的同时,引入了Composition API、响应式系统重构等重大革新。相较于Vue2,Vue3在性能上实现了2-4倍的提升,主要体现在:
典型应用场景包括:需要高性能响应的实时数据看板、复杂状态管理的中后台系统、以及追求轻量化的移动端H5应用。某电商平台的商品详情页重构案例显示,Vue3使首屏渲染时间从1.2s降至0.7s。
import { ref, reactive } from 'vue'// 基本类型响应式const count = ref(0) // 通过.value访问count.value++// 对象类型响应式const state = reactive({user: { name: 'John' },items: [1, 2, 3]})state.user.name = 'Doe' // 自动触发更新
import { computed, watch } from 'vue'const doubled = computed(() => count.value * 2)// 基础侦听watch(count, (newVal, oldVal) => {console.log(`值从${oldVal}变为${newVal}`)})// 深度侦听对象watch(() => state.user,(newUser) => {console.log('用户信息变更:', newUser)},{ deep: true })
push()/pop()等变异方法自动触发更新toRefs保持响应性
const { user, items } = toRefs(state)
readonly()创建不可修改的响应式对象
import { onMounted, ref } from 'vue'export function useCounter() {const count = ref(0)function increment() {count.value++}onMounted(() => {console.log('组件挂载')})return { count, increment }}
Vue3提供21个生命周期钩子,按执行阶段分类:
beforeCreate → created → onBeforeMount → onMountedonBeforeUpdate → onUpdatedonBeforeUnmount → onUnmounted
// useFetch.jsexport function useFetch(url) {const data = ref(null)const error = ref(null)async function fetchData() {try {const response = await fetch(url)data.value = await response.json()} catch (err) {error.value = err}}return { data, error, fetchData }}
v-if/v-else/v-show的差异(v-if有切换开销,v-show有初始渲染开销)v-for的key最佳实践(使用唯一ID而非索引).prevent修饰符等语法糖| 通信方式 | 适用场景 | 示例 |
|---|---|---|
| Props | 父子组件向下传值 | :message="parentMsg" |
| Emits | 子组件向父组件通信 | @update="handleUpdate" |
| Provide/Inject | 跨层级组件传值 | provide('theme', 'dark') |
| 事件总线 | 任意组件通信(Vue3推荐mitt库) | mitt().emit('event') |
<slot></slot><slot name="header"></slot>
{{ slotProps.user.name }}
# 五、实战案例解析## 1. 表单验证组件```javascript// useForm.jsexport function useForm(initialState) {const form = reactive({ ...initialState })const errors = reactive({})function validateField(field, rules) {errors[field] = rules.reduce((acc, rule) => {return acc || rule.validator(form[field]) ? '' : rule.message}, '')}return { form, errors, validateField }}
// useInfiniteScroll.jsexport function useInfiniteScroll(fetchFn) {const items = ref([])const loading = ref(false)const hasMore = ref(true)async function loadMore() {if (loading.value || !hasMore.value) returnloading.value = trueconst newItems = await fetchFn()items.value = [...items.value, ...newItems]hasMore.value = newItems.length > 0loading.value = false}return { items, loading, hasMore, loadMore }}
// themeContext.jsimport { createContext } from 'vue'export const ThemeContext = createContext({theme: 'light',toggleTheme: () => {}})// App.vueconst theme = ref('light')function toggleTheme() {theme.value = theme.value === 'light' ? 'dark' : 'light'}provide(ThemeContext, { theme, toggleTheme })
unplugin-vue-components自动导入组件
const routes = [{path: '/dashboard',component: () => import('./views/Dashboard.vue')}]
vue-virtual-scroller@vue/compat构建模式逐步迁移this指向变化、过滤器废弃等
interface Props {title: stringcount?: number}const props = withDefaults(defineProps<Props>(), {count: 0})
本文通过系统化的知识体系构建,帮助开发者建立Vue3开发的完整认知框架。实际开发中建议遵循”小步快跑”原则,从简单组件开始逐步掌握组合式API的编程思想。对于复杂项目,推荐结合Pinia进行状态管理,使用Vue Router处理路由逻辑,形成完整的技术栈解决方案。