Vue
基於 Vue 3.5。一律使用 Composition API 搭配 <script setup lang="ts">。
偏好設定
- 偏好 TypeScript 而非 JavaScript
- 偏好
<script setup lang="ts"> 而非 <script>
- 為效能考量,若不需要深層響應,優先使用
shallowRef 而非 ref
- 一律使用 Composition API 而非 Options API
- 不鼓勵使用響應式 Props 解構
核心
| 主題 | 說明 | 參考資料 |
|---|
| Script Setup 與巨集 | <script setup>、defineProps、defineEmits、defineModel、defineExpose、defineOptions、defineSlots、泛型 | script-setup-macros |
| 響應性與生命週期 | ref、shallowRef、computed、watch、watchEffect、effectScope、生命週期鉤子、composables | core-new-apis |
功能
快速參考
元件範本
<script setup lang="ts">
import { ref, computed, watch, onMounted } from 'vue'
const props = defineProps<{
title: string
count?: number
}>()
const emit = defineEmits<{
update: [value: string]
}>()
const model = defineModel<string>()
const doubled = computed(() => (props.count ?? 0) * 2)
watch(() => props.title, (newVal) => {
console.log('Title changed:', newVal)
})
onMounted(() => {
console.log('Component mounted')
})
</script>
<template>
<div>{{ title }} - {{ doubled }}</div>
</template>
關鍵匯入
import { ref, shallowRef, computed, reactive, readonly, toRef, toRefs, toValue } from 'vue'
import { watch, watchEffect, watchPostEffect, onWatcherCleanup } from 'vue'
import { onMounted, onUpdated, onUnmounted, onBeforeMount, onBeforeUpdate, onBeforeUnmount } from 'vue'
import { nextTick, defineComponent, defineAsyncComponent } from 'vue'