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、生命周期钩子、组合式函数 | 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('标题已更改:', newVal)
})
onMounted(() => {
console.log('组件已挂载')
})
</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'