Vue3 知識點總結
1. 核心概念
1.1 Composition API
1.1.1 setup 函數
setup是Vue3中的新的配置項,是組件內使用Composition API的入口 在setup中定義的變量和方法需要return才能在模板中使用 setup執行時機在beforeCreate之前,this不可用
export default { setup ( ) { const count = ref ( 0 ) const increment = ( ) => count. value++ return { count, increment} }
}
1.1.2 響應式API
ref
用于基本類型的響應式 在setup中需要.value訪問 在模板中自動解包
const count = ref ( 0 )
console. log ( count. value)
reactive
const state = reactive ( { count: 0 , list: [ ]
} )
toRef 和 toRefs
toRef: 為源響應式對象上的屬性新建ref toRefs: 將響應式對象轉換為普通對象,其中每個屬性都是ref
const state = reactive ( { foo: 1 , bar: 2
} )
const fooRef = toRef ( state, 'foo' )
const stateRefs = toRefs ( state)
1.2 生命周期鉤子
setup(): 組件創建前執行 onBeforeMount(): 組件掛載前 onMounted(): 組件掛載后 onBeforeUpdate(): 組件更新前 onUpdated(): 組件更新后 onBeforeUnmount(): 組件卸載前 onUnmounted(): 組件卸載后
import { onMounted } from 'vue' export default { setup ( ) { onMounted ( ( ) => { console. log ( '組件已掛載' ) } ) }
}
1.3 依賴注入
provide/inject
provide ( 'key' , value)
const value = inject ( 'key' )
2. 新特性
2.1 Teleport
將組件內容渲染到指定DOM節點 常用于模態框、彈出層等
<teleport to="body"><div class="modal"><!-- 模態框內容 --></div>
</teleport>
2.2 Fragments
<template><header>...</header><main>...</main><footer>...</footer>
</template>
2.3 Suspense
<suspense><template #default><async-component /></template><template #fallback><loading-component /></template>
</suspense>
3. 狀態管理
3.1 Pinia
Vue3推薦的狀態管理方案 支持TypeScript 輕量級、模塊化
import { defineStore } from 'pinia' export const useCounterStore = defineStore ( 'counter' , { state : ( ) => ( { count: 0 } ) , actions: { increment ( ) { this . count++ } }
} )
4. 性能優化
4.1 靜態提升
4.2 Patch Flag
4.3 Tree Shaking
5. TypeScript支持
5.1 類型定義
interface User { id: number name: string
} const user = ref < User> ( { id: 1 , name: 'Tom' } )
5.2 組件Props類型
defineProps < { title: string count: number
} > ( )
6. 工程化實踐
6.1 Vite
更快的開發服務器啟動 更快的模塊熱更新 優化的構建輸出
6.2 單文件組件
<script setup lang="ts">
import { ref } from 'vue'const count = ref(0)
</script><template><button @click="count++">{{ count }}</button>
</template>
6.3 組件設計原則
單一職責 可復用性 Props向下,Events向上 組件通信規范
7. 最佳實踐
7.1 代碼組織
使用組合式函數(Composables) 邏輯復用和抽象 目錄結構規范
7.2 性能考慮
合理使用computed和watch 避免不必要的組件渲染 使用v-show代替v-if(頻繁切換)
7.3 錯誤處理
7.4 自定義指令
app. directive ( 'debounce' , { mounted ( el, binding ) { const delay = binding. value || 300 let timer = null el. addEventListener ( 'click' , ( ) => { if ( timer) clearTimeout ( timer) timer = setTimeout ( ( ) => { binding. value ( ) } , delay) } ) }
} )
7.5 動畫與過渡
v-enter-from/v-leave-to transition組件 transition-group列表過渡
<template><transition name="fade"><div v-if="show">Content</div></transition>
</template><style>
.fade-enter-active,
.fade-leave-active {transition: opacity 0.5s;
}
.fade-enter-from,
.fade-leave-to {opacity: 0;
}
</style>
7.6 組合式函數(Composables)
import { ref, onMounted } from 'vue' export function useCounter ( initialValue = 0 ) { const count = ref ( initialValue) const increment = ( ) => count. value++ const decrement = ( ) => count. value-- onMounted ( ( ) => { console. log ( 'Counter mounted' ) } ) return { count, increment, decrement}
}
const { count, increment } = useCounter ( )
7.7 與其他技術棧集成
7.7.1 Vue3 + TypeScript
interface Props { message: string count? : number
} defineProps < Props> ( )
interface UseUserReturn { user: Ref< User | null > loading: Ref< boolean > error: Ref< Error | null > fetchUser : ( id: number ) => Promise < void >
} function useUser ( ) : UseUserReturn {
}
7.7.2 Vue3 + Vite + TailwindCSS
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import tailwindcss from 'tailwindcss' export default defineConfig ( { plugins: [ vue ( ) ] , css: { postcss: { plugins: [ tailwindcss] } }
} )
7.7.3 Vue3 + Jest
import { mount } from '@vue/test-utils'
import Counter from './Counter.vue' test ( 'increments value on click' , async ( ) => { const wrapper = mount ( Counter) await wrapper. find ( 'button' ) . trigger ( 'click' ) expect ( wrapper. text ( ) ) . toContain ( '1' )
} )
8. 高級組件模式
8.1 動態組件
<template><component :is="currentComponent" v-bind="props" />
</template><script setup>
import { shallowRef } from 'vue'const currentComponent = shallowRef(null)
const props = ref({})// 異步加載組件
async function loadComponent(name) {const component = await import(`./components/${name}.vue`)currentComponent.value = component.default
}
</script>
8.2 遞歸組件
<!-- TreeNode.vue -->
<template><div class="tree-node"><div @click="toggle">{{ node.label }}</div><div v-if="isExpanded && node.children" class="children"><tree-nodev-for="child in node.children":key="child.id":node="child"/></div></div>
</template><script setup>
const props = defineProps(['node'])
const isExpanded = ref(false)
const toggle = () => isExpanded.value = !isExpanded.value
</script>
8.3 高階組件(HOC)
import { h, defineComponent } from 'vue' export function withLoading ( WrappedComponent) { return defineComponent ( { props: [ 'loading' , ... WrappedComponent. props] , setup ( props, { attrs, slots } ) { return ( ) => props. loading? h ( 'div' , 'Loading...' ) : h ( WrappedComponent, { ... attrs } , slots) } } )
}
9. 性能優化最佳實踐
9.1 大列表優化
<script setup>
import { useVirtualList } from '@vueuse/core'const list = ref(Array.from({ length: 10000 }, (_, i) => ({ id: i, text: `Item ${i}` })))
const { list: virtualList, containerProps, wrapperProps } = useVirtualList(list, {itemHeight: 40,overscan: 10
})
</script><template><div v-bind="containerProps" class="container"><div v-bind="wrapperProps"><div v-for="item in virtualList" :key="item.id" class="item">{{ item.text }}</div></div></div>
</template>
9.2 組件懶加載
const routes = [ { path: '/dashboard' , component : ( ) => import ( './views/Dashboard.vue' ) }
]
const MyComponent = defineAsyncComponent ( ( ) => import ( './components/MyComponent.vue' )
)
9.3 計算屬性緩存
const expensiveComputed = computed ( ( ) => { return list. value. filter ( item => { return complexProcess ( item) } )
} )
const fullName = computed ( { get ( ) { return ` ${ firstName. value} ${ lastName. value} ` } , set ( newValue) { [ firstName. value, lastName. value] = newValue. split ( ' ' ) }
} )
10. 與Vue2的主要區別
10.1 核心架構
使用Proxy代替Object.defineProperty實現響應式 重寫虛擬DOM實現,性能提升100% 模板編譯優化,支持靜態提升 更好的TypeScript支持,內置類型聲明
10.2 API差異
Composition API vs Options API 新的生命周期鉤子 移除filter和 o n 、 on、 o n 、 off等API setup函數替代beforeCreate和created
10.3 模板語法
v-model的使用變化(modelValue + update:modelValue) 支持多個v-model綁定 Teleport、Suspense等新特性 片段(Fragments)支持多根節點
10.4 響應式系統
ref和reactive的顯式聲明 更好的響應式解構支持(toRefs) 響應式數據的調試能力增強 更細粒度的響應式控制