Vue3最新版本所有 API 完整列表及代码示例

Vue3最新版本所有 API 完整列表及代码示例Vue 3 API 全量指南 (v3.5.22)

基于 Vue 3.5.22 官方文档整理,覆盖当前稳定版全部公开 API。内容按官方索引分组,保证“一个都不少”,并补充用途说明、调用签名、要点和示例便于查阅。


全局 API

应用实例

createApp()

  • 功能:以根组件创建新的独立应用实例。

  • 签名:

    function createApp(rootComponent: Component, rootProps?: object): App
  • 要点:每个实例拥有独立的配置和插件注册;rootProps 会作为 props 传入根组件。

  • 示例:

    import { createApp } from 'vue'
    import App from './App.vue'
    
    const app = createApp(App, { defaultTab: 'home' })
    app.mount('#app')

createSSRApp()

  • 功能:为服务端渲染创建应用实例。

  • 区别:内部默认挂载 SSR renderer,避免因 DOM API 缺失造成错误。

  • 示例:

    import { createSSRApp } from 'vue'
    import App from './App.vue'
    
    export function createApp() {
      const app = createSSRApp(App)
      return { app }
    }

app.mount()

  • 功能:将应用渲染到指定 DOM 容器。

  • 签名:

    app.mount(rootContainer: Element | string): ComponentPublicInstance
  • 要点:在客户端仅可调用一次;返回根组件实例。

  • 示例:

    const vm = app.mount('#app-root')
    // 可访问通过 expose 暴露的方法
    vm.focusInput?.()

app.unmount()

  • 功能:手动卸载应用,释放响应式副作用与挂载的 DOM。

  • 适用:微前端或离开 SPA 时执行清理。

  • 示例:

    // 某些场景下需要在离开页面时卸载
    window.addEventListener('beforeunload', () => {
      app.unmount()
    })

app.onUnmount()

  • 功能:注册在应用卸载时执行的回调。

  • 用法:

    const stop = analytics.start()
    app.onUnmount(() => stop())

app.component()

  • 功能:全局注册或获取组件。

  • 签名:

    app.component(name: string, component?: Component): App | Component
  • 说明:无第二参数时返回已注册的组件。

app.directive()

  • 功能:全局注册/获取自定义指令。

  • 使用:

    app.directive('focus', {
      mounted(el) { el.focus() }
    })

app.use()

  • 功能:安装插件或 Vue Router、Pinia 等库。

  • 插件函数会收到 app 实例与可选参数。

  • 示例:

    import { createPinia } from 'pinia'
    
    const pinia = createPinia()
    app.use(pinia)

app.mixin()

  • 功能:注册全局混入,影响之后创建的所有组件。

  • 谨慎:可能造成全局副作用,推荐用于全局注入 mixin。

  • 示例:

    app.mixin({
      created() {
        console.debug(`[${this.$options.name}] created`)
      }
    })

app.provide()

  • 功能:在根作用域提供依赖,供全局 inject 使用。

  • 示例:

    app.provide('apiBase', 'https://api.example.com')
    app.provide(Symbol('theme'), ref('dark'))

app.runWithContext()

  • 功能:以应用上下文包裹回调,常用于把组合式 API 用于应用外部(如插件)。

  • 签名:app.runWithContext(fn: () => T): T

  • 示例:

    app.runWithContext(() => {
      // 在应用上下文里可安全调用 inject / useXxx 组合函数
      const { t } = useI18n()
      console.log(t('message'))
    })

app.version

  • 内容:当前应用使用的 Vue 版本字符串。

  • 示例:

    console.info(`Running on Vue ${app.version}`)

app.config

  • 功能:全局配置对象入口。

  • 常规属性:errorHandlerwarnHandlerglobalPropertiescompilerOptions 等。

  • 示例:

    app.config.warnHandler = (msg, instance, trace) => {
      reportWarning({ msg, trace })
    }

app.config.errorHandler

  • 用途:捕获组件渲染或生命周期内错误。

  • 签名:(err, instance, info) => void

  • 推荐记录日志或展示兜底 UI。

  • 示例:

    app.config.errorHandler = (err, instance, info) => {
      sendToSentry(err, { info, component: instance?.type })
      showToast('发生了一些错误,请稍后再试')
    }

app.config.warnHandler

  • 功能:拦截运行时警告。

  • 签名:(msg, instance, trace) => void

  • 适合在开发环境自定义提示。

  • 示例:

    app.config.warnHandler = (msg, instance, trace) => {
      if (process.env.NODE_ENV === 'development') {
        console.warn(`[Vue warn]: ${msg}\n${trace}`)
      }
    }

app.config.performance

  • 功能:在开发环境开启性能追踪,配合浏览器 devtools。

  • 示例:

    if (import.meta.env.DEV) {
      app.config.performance = true
    }

app.config.compilerOptions

  • 功能:影响模板编译行为的配置集合。

app.config.compilerOptions.isCustomElement
  • 功能:标记哪些标签应视作自定义元素,避免被 Vue 解析。

  • 示例:

    app.config.compilerOptions.isCustomElement = tag => tag.startsWith('ion-')
app.config.compilerOptions.whitespace
  • 作用:控制空白压缩方式,'condense' | 'preserve'

  • 示例:

    app.config.compilerOptions.whitespace = 'preserve'
app.config.compilerOptions.delimiters
  • 作用:自定义插值分隔符,如 ['${', '}']

  • 示例:

    app.config.compilerOptions.delimiters = ['${', '}']
app.config.compilerOptions.comments
  • 作用:决定生产环境是否保留 HTML 注释。

  • 示例:

    app.config.compilerOptions.comments = true

app.config.globalProperties

  • 功能:向所有组件实例注入属性或方法。

  • 示例:

    app.config.globalProperties.$http = axiosInstance
    app.config.globalProperties.$formatDate = (value: Date) =>
      dayjs(value).format('YYYY-MM-DD')

app.config.optionMergeStrategies

  • 功能:自定义选项的合并策略,用于插件或框架扩展。

  • 示例:

    app.config.optionMergeStrategies.permissions = (toVal = [], fromVal = []) => [
      ...new Set([...toVal, ...fromVal])
    ]

app.config.idPrefix

  • 功能:为 SSR 生成的自动 ID 添加前缀,避免多个应用冲突。

  • 示例:

    app.config.idPrefix = 'app-a-'

app.config.throwUnhandledErrorInProduction

  • 功能:控制生产环境未捕获错误是否抛出(默认 false)。

  • 示例:

    app.config.throwUnhandledErrorInProduction = true

通用 API

通用

version

  • 内容:运行时导出的 Vue 版本号,与 app.version 一致。

  • 示例:

    import { version } from 'vue'
    
    console.log(`Using Vue runtime: ${version}`)

nextTick()

  • 功能:等待下一个 DOM 更新周期。

  • 签名:nextTick(callback?, thisArg?) => Promise<void>

  • 示例:

    import { nextTick } from 'vue'
    await nextTick()
    console.log('DOM 已更新')

defineComponent()

  • 功能:为组合式或选项式组件提供类型推断与 IDE 支持。

  • 示例:

    import { defineComponent, ref } from 'vue'
    
    export default defineComponent({
      name: 'CounterButton',
      setup() {
        const count = ref(0)
        const increment = () => count.value++
        return { count, increment }
      }
    })

defineAsyncComponent()

  • 功能:声明懒加载组件。

  • 支持:loaderloadingComponenterrorComponenttimeoutsuspensible 等选项。

  • 示例:

    import { defineAsyncComponent } from 'vue'
    
    const AsyncChart = defineAsyncComponent({
      loader: () => import('@/components/Chart.vue'),
      loadingComponent: () => 'Loading...',
      errorComponent: () => 'Load failed',
      delay: 200,
      timeout: 10_000,
      suspensible: true
    })

组合式 API

setup()

  • 功能:组合式 API 入口,组件在实例化前调用。

基本使用

  • 返回对象或渲染函数给模板使用。

  • 示例:

    export default {
      setup() {
        const count = ref(0)
        return { count }
      }
    }

访问 Props

  • setup 第一个参数为响应式 props,只读。

  • 通过解构需配合 toRefstoRef 保持响应式。

  • 示例:

    export default {
      props: { initial: Number },
      setup(props) {
        const { initial } = toRefs(props)
        const count = ref(initial.value ?? 0)
        watch(initial, value => (count.value = value))
        return { count }
      }
    }

Setup 上下文

  • 第二个参数包含 { attrs, slots, emit, expose }

  • 可使用 expose 指定对父组件暴露的方法。

  • 示例:

    export default {
      setup(props, { attrs, slots, emit, expose }) {
        const toggle = () => emit('toggle')
        expose({ toggle })
        return () => (
          <button class={attrs.class} onClick={toggle}>
            {slots.default?.() ?? 'Toggle'}
          </button>
        )
      }
    }

与渲染函数一起使用

  • setup 可返回函数并借助 h 构建 VNode,实现函数式组件。

  • 示例:

    import { h } from 'vue'
    
    export default {
      props: { tag: { type: String, default: 'div' } },
      setup(props, { slots }) {
        return () => h(props.tag, { class: 'wrapper' }, slots.default?.())
      }
    }

响应式: 核心

ref()

  • 创建包含 .value 的响应式引用,支持原始类型与对象。

  • 示例:

    const count = ref(0)
    count.value++
    const inputEl = ref<HTMLInputElement | null>(null)
    onMounted(() => inputEl.value?.focus())

computed()

  • 声明基于其他响应式值的派生状态,默认惰性缓存,支持 get/set

  • 示例:

    const price = ref(99.5)
    const quantity = ref(2)
    const total = computed(() => price.value * quantity.value)
    const formatted = computed({
      get: () => `$${total.value.toFixed(2)}`,
      set(value: string) {
        price.value = Number.parseFloat(value.replace('$', ''))
      }
    })

reactive()

  • 将对象转为深层响应式代理,返回 Proxy。

  • 示例:

    const state = reactive({
      user: { name: 'Alice', age: 18 },
      tags: ['vue', 'composition-api']
    })
    state.tags.push('typescript')

readonly()

  • 创建不可变视图;对原对象的变更仍会反映到只读代理。

  • 示例:

    const mutable = reactive({ role: 'admin' })
    const safe = readonly(mutable)
    // safe.role = 'user' // ❌ 抛出警告
    mutable.role = 'editor' // ✅ safe.role 同步为 editor

watchEffect()

  • 自动收集依赖并立即执行回调,适合副作用逻辑。

  • 示例:

    const stop = watchEffect(onInvalidate => {
      const controller = new AbortController()
      fetch(`/api/user/${userId.value}`, { signal: controller.signal })
      onInvalidate(() => controller.abort())
    })
    onBeforeUnmount(stop)

watchPostEffect()

  • watchEffect 类似但在组件更新后执行。

  • 示例:

    watchPostEffect(() => {
      console.log('DOM 已更新,最新高度:', panelRef.value?.offsetHeight)
    })

watchSyncEffect()

  • 同步执行副作用,适用于读取同步 DOM。

  • 示例:

    watchSyncEffect(() => {
      // 同步读取,确保值与当前帧 DOM 对齐
      cachedRect.value = elementRef.value?.getBoundingClientRect()
    })

watch()

  • 显式侦听源(ref、getter、数组等),提供旧值与 onCleanup

  • 示例:

    watch(
      () => [form.name, form.email],
      ([name, email], [prevName, prevEmail], onCleanup) => {
        const controller = new AbortController()
        onCleanup(() => controller.abort())
        validateAsync({ name, email }, controller.signal)
      },
      { immediate: true, deep: false }
    )

onWatcherCleanup()

  • 别名 onInvalidate,在侦听器中注册清理函数。

  • 示例:

    watchEffect(onCleanup => {
      const timer = setInterval(refresh, 5000)
      onCleanup(() => clearInterval(timer))
    })

响应式: 工具

isRef()

  • 判断值是否为 ref

  • 示例:

    const maybeRef: unknown = getValue()
    if (isRef(maybeRef)) {
      console.log('current', maybeRef.value)
    }

unref()

  • 若是 ref 返回 .value,否则直接返回原值。

  • 示例:

    function normalize<T>(value: T | Ref<T>) {
      return unref(value)
    }

toRef()

  • 将响应式对象属性转为 ref;若属性不存在也会创建。

  • 示例:

    const settings = reactive({ locale: 'zh-CN' })
    const locale = toRef(settings, 'locale')
    locale.value = 'en-US'

toValue()

  • Vue 3.3+:统一读取 MaybeRef 或 getter 值,常配合函数式参数。

  • 示例:

    function useMaybeRef<T>(input: MaybeRefOrGetter<T>) {
      return computed(() => toValue(input))
    }

toRefs()

  • reactive 对象的每个属性转换为 ref。

  • 示例:

    const state = reactive({ title: 'Guide', count: 0 })
    const { title, count } = toRefs(state)
    count.value++

isProxy()

  • 检测对象是否由 reactive/readonly 创建。

  • 示例:

    console.log(isProxy(reactive({}))) // true
    console.log(isProxy({})) // false

isReactive()

  • 判断对象是否为响应式代理。

  • 示例:

    const state = reactive({ ok: true })
    console.log(isReactive(state)) // true

isReadonly()

  • 判断是否为只读代理。

  • 示例:

    const original = readonly({ locked: true })
    console.log(isReadonly(original)) // true

响应式: 进阶

shallowRef()

  • 仅跟踪 .value 的替换,不深度侦测对象内部。

  • 示例:

    const chartInstance = shallowRef<Chart | null>(null)
    chartInstance.value = createChart()

triggerRef()

  • 手动触发 shallowRef 的依赖更新。

  • 示例:

    chartInstance.value!.resize()
    triggerRef(chartInstance)

customRef()

  • 自定义对 .value 的跟踪与触发逻辑,如防抖。

  • 示例:

    function useDebouncedRef<T>(initial: T, delay = 300) {
      return customRef((track, trigger) => {
        let value = initial
        let timer: number | undefined
        return {
          get() {
            track()
            return value
          },
          set(newValue) {
            clearTimeout(timer)
            timer = window.setTimeout(() => {
              value = newValue
              trigger()
            }, delay)
          }
        }
      })
    }

shallowReactive()

  • 仅代理对象顶层属性,内部保持原值。

  • 示例:

    const config = shallowReactive({
      options: new Map(),
      theme: { primary: '#42b883' }
    })
    config.theme.primary = '#35495e' // 不会触发响应更新
    config.theme = { primary: '#ff9900' } // 会触发

shallowReadonly()

  • 顶层只读代理,内部属性仍可变更。

  • 示例:

    const runtimeOptions = shallowReadonly({
      endpoints: [],
      meta: { version: 1 }
    })
    runtimeOptions.meta.version = 2 // ✅
    // runtimeOptions.endpoints = [] // ❌

toRaw()

  • 取得响应式代理的原始对象,慎用于调试或与非响应式代码交互。

  • 示例:

    const state = reactive({ cache: new Map() })
    const rawMap = toRaw(state.cache)
    rawMap.set('token', 'abc123')

markRaw()

  • 标记对象永远不被代理,常用于第三方类实例。

  • 示例:

    const socket = markRaw(createSocketConnection())
    const state = reactive({ socket })

effectScope()

  • 创建副作用作用域,用于集中停止内部 watch/effect。

  • 示例:

    const scope = effectScope()
    scope.run(() => {
      watchEffect(() => syncToLocalStorage(state.value))
    })
    onBeforeUnmount(() => scope.stop())

getCurrentScope()

  • 返回当前激活的 effectScope,若无则为 undefined

  • 示例:

    effectScope().run(() => {
      console.log(!!getCurrentScope()) // true
    })

onScopeDispose()

  • 在当前作用域销毁时执行回调,常用于组合式函数。

  • 示例:

    export function useInterval(fn: () => void, delay: number) {
      const timer = setInterval(fn, delay)
      onScopeDispose(() => clearInterval(timer))
    }

生命周期钩子

onMounted()

  • 组件挂载后执行。

  • 示例:

    onMounted(() => {
      fetchList()
      focusFirstInput()
    })

onUpdated()

  • 响应式更新后执行。

  • 示例:

    onUpdated(() => {
      console.log('更新后的节点高度', panelRef.value?.offsetHeight)
    })

onUnmounted()

  • 实例卸载后执行清理。

  • 示例:

    onUnmounted(() => {
      unsubscribe()
      clearInterval(timerId)
    })

onBeforeMount()

  • 首次挂载前触发。

  • 示例:

    onBeforeMount(() => {
      console.time('first-render')
    })

onBeforeUpdate()

  • 响应式更新引发 DOM 变更前触发。

  • 示例:

    onBeforeUpdate(() => {
      previousHeight.value = panelRef.value?.offsetHeight ?? 0
    })

onBeforeUnmount()

  • 实例卸载前调用。

  • 示例:

    onBeforeUnmount(() => {
      analytics.flush()
    })

onErrorCaptured()

  • 捕获子组件错误,可选择返回 false 阻止冒泡。

  • 示例:

    onErrorCaptured((err, instance, info) => {
      logError(err, info)
      return false // 继续向上传播
    })

onRenderTracked()

  • 调试钩子:依赖被追踪时调用。

  • 示例:

    onRenderTracked(event => {
      console.debug('tracked', event.key, event.target)
    })

onRenderTriggered()

  • 调试钩子:依赖触发更新时调用。

  • 示例:

    onRenderTriggered(event => {
      console.debug('triggered', event.key, event.type)
    })

onActivated()

  • <KeepAlive> 激活缓存组件时触发。

  • 示例:

    onActivated(() => {
      resumeSubscription()
    })

onDeactivated()

  • <KeepAlive> 组件失活时触发。

  • 示例:

    onDeactivated(() => {
      pauseSubscription()
    })

onServerPrefetch()

  • SSR 渲染前执行异步数据获取。

  • 示例:

    onServerPrefetch(async () => {
      await store.fetchInitialData()
    })

依赖注入

provide()

  • 在当前组件向下提供依赖,值可为响应式。

  • 示例:

    const theme = ref<'light' | 'dark'>('light')
    provide(ThemeSymbol, theme)

inject()

  • 在后代组件注入依赖,支持默认值或工厂函数。

  • 示例:

    const theme = inject(ThemeSymbol, ref('light'))
    const apiBase = inject('apiBase', () => 'https://api.example.com', true)

hasInjectionContext()

  • 判断当前是否处于可用的注入上下文(组件或 app.runWithContext 内)。

  • 示例:

    if (hasInjectionContext()) {
      const locale = inject('locale')
      console.log(locale)
    }

辅助

useAttrs()

  • 获取当前组件透传的非 props attribute,对象是响应式快照。

  • 示例:

    const attrs = useAttrs()
    return () => <button {...attrs}>Click me</button>

useSlots()

  • 获得 slots 渲染函数集合。

  • 示例:

    const slots = useSlots()
    return () => <section>{slots.header?.()} {slots.default?.()}</section>

useModel()

  • Vue 3.4+:组合式版本的 v-model 操作器,可处理参数与默认值。

  • 示例:

    const [value, setValue] = useModel(props, 'modelValue', emit, {
      defaultValue: ''
    })
    setValue('updated')

useTemplateRef()

  • Vue 3.3+:与 <template ref> 搭配,类型安全获取模板 ref。

  • 示例:

    const modal = useTemplateRef<HTMLDialogElement>('modal')
    const open = () => modal.value?.showModal()

useId()

  • 生成稳定的唯一 ID,支持 SSR hydration。

  • 示例:

    const inputId = useId()
    return { inputId }

选项式 API

状态选项

data

  • 组件实例数据函数,返回对象会与响应式系统集成。

  • 示例:

    export default {
      data() {
        return {
          count: 0,
          loading: false
        }
      }
    }

props

  • 声明组件可接收的 prop 名称及类型/默认值验证。

  • 示例:

    export default {
      props: {
        title: { type: String, required: true },
        pageSize: { type: Number, default: 10 }
      }
    }

computed

  • 对象形式声明计算属性,等价于组合式 computed

  • 示例:

    export default {
      data: () => ({ price: 120, quantity: 1 }),
      computed: {
        total() {
          return this.price * this.quantity
        }
      }
    }

methods

  • 声明实例方法,自动绑定 this 为组件实例。

  • 示例:

    export default {
      methods: {
        increment() {
          this.count++
        }
      },
      data: () => ({ count: 0 })
    }

watch

  • 定义侦听器,可使用字符串路径、函数或数组。

  • 示例:

    export default {
      watch: {
        value(newVal, oldVal) {
          console.log('changed', newVal, oldVal)
        },
        'form.email': {
          handler(value) {
            this.validateEmail(value)
          },
          immediate: true
        }
      }
    }

emits

  • 声明允许发出的自定义事件,用于开发时校验。

  • 示例:

    export default {
      emits: ['submit', 'cancel'],
      methods: {
        submit() {
          this.$emit('submit', { value: this.value })
        }
      }
    }

expose

  • 选项式中显式暴露实例属性给父组件(等价于组合式 expose)。

  • 示例:

    export default {
      expose: ['focus'],
      methods: {
        focus() {
          this.$refs.input.focus()
        }
      }
    }

渲染选项

template

  • 指定内联模板字符串或挂载在 DOM 中的模板选择器。

  • 示例:

    export default {
      template: `<button @click="increment">Clicked {{ count }} times</button>`,
      data: () => ({ count: 0 }),
      methods: { increment() { this.count++ } }
    }

render

  • 自定义渲染函数,直接返回 VNode。

  • 示例:

    import { h } from 'vue'
    
    export default {
      render() {
        return h('h1', { class: 'title' }, this.title)
      },
      props: { title: String }
    }

compilerOptions

  • 组件级别编译选项,覆盖全局设置。

  • 示例:

    export default {
      compilerOptions: {
        delimiters: ['${', '}']
      }
    }

slots

  • 仅限用于定义函数式组件的可选项,声明 slot 渲染函数。

  • 示例:

    export default {
      slots: {
        default: (props: { count: number }) => [`count: ${props.count}`]
      }
    }

生命周期选项

beforeCreate

  • 选项式初始化钩子,此时 datacomputed 尚未解析。

  • 示例:

    export default {
      beforeCreate() {
        console.log('beforeCreate called')
      }
    }

created

  • 选项式初始化完成钩子,可访问响应式数据与方法。

  • 示例:

    export default {
      data: () => ({ ready: false }),
      created() {
        this.ready = true
      }
    }

beforeMount

  • 在首次挂载前触发,适合最后操作渲染前状态。

  • 示例:

    export default {
      beforeMount() {
        console.time('mount')
      }
    }

mounted

  • 组件首次渲染后触发,可安全访问 DOM。

  • 示例:

    export default {
      mounted() {
        this.$refs.input.focus()
      }
    }

beforeUpdate

  • 响应式更新引发重新渲染前触发。

  • 示例:

    export default {
      beforeUpdate() {
        this.prevHeight = this.$el.offsetHeight
      }
    }

updated

  • 更新完成后触发,可对最新 DOM 作响应。

  • 示例:

    export default {
      updated() {
        console.log('new height', this.$el.offsetHeight)
      }
    }

beforeUnmount

  • 实例卸载前调用,可执行清理。

  • 示例:

    export default {
      beforeUnmount() {
        this.flushEvents()
      }
    }

unmounted

  • 实例卸载完成后调用。

  • 示例:

    export default {
      unmounted() {
        console.log('component destroyed')
      }
    }

errorCaptured

  • 捕获错误,与组合式 onErrorCaptured 相同。

  • 示例:

    export default {
      errorCaptured(err, instance, info) {
        reportError(err, info)
        return false
      }
    }

renderTracked

  • 调试钩子,依赖被追踪时触发。

  • 示例:

    export default {
      renderTracked(e) {
        console.debug('tracked', e.key)
      }
    }

renderTriggered

  • 调试钩子,依赖变更触发重新渲染时调用。

  • 示例:

    export default {
      renderTriggered(e) {
        console.debug('triggered', e.key)
      }
    }

activated

  • <KeepAlive> 缓存组件重新激活时触发。

  • 示例:

    export default {
      activated() {
        this.resume()
      }
    }

deactivated

  • <KeepAlive> 组件被切换并缓存时触发。

  • 示例:

    export default {
      deactivated() {
        this.pause()
      }
    }

serverPrefetch

  • SSR 数据预取。

  • 示例:

    export default {
      async serverPrefetch() {
        await this.$store.dispatch('fetch')
      }
    }

组合选项

provide

  • 选项式语法与组合式一致,支持对象或函数返回。

  • 示例:

    export default {
      provide() {
        return { theme: this.theme }
      },
      data: () => ({ theme: ref('light') })
    }

inject

  • 选项式 inject,支持数组字符串或对象语法设置默认值。

  • 示例:

    export default {
      inject: {
        theme: { from: 'theme', default: 'light' },
        apiBase: { from: 'apiBase', default: 'https://api.example.com' }
      }
    }

mixins

  • 混入数组,内容会合并进组件选项。

  • 示例:

    const focusMixin = {
      mounted() {
        this.$el.focus?.()
      }
    }
    
    export default {
      mixins: [focusMixin]
    }

extends

  • 基于继承扩展现有组件选项。

  • 示例:

    const base = { methods: { log() { console.log('base') } } }
    
    export default {
      extends: base
    }

其他杂项

name

  • 组件名称,影响 devtools 展示与递归组件。

  • 示例:

    export default {
      name: 'UserCard'
    }

inheritAttrs

  • 控制非 props attribute 是否自动挂载到根元素。

  • 示例:

    export default {
      inheritAttrs: false,
      render() {
        return h('div', { class: 'wrapper' }, [
          h('input', { ...this.$attrs })
        ])
      }
    }

components

  • 局部注册子组件。

  • 示例:

    import Dialog from './Dialog.vue'
    
    export default {
      components: { Dialog }
    }

directives

  • 局部注册指令。

  • 示例:

    const focus = {
      mounted(el: HTMLElement) {
        el.focus()
      }
    }
    
    export default {
      directives: { focus }
    }

组件实例

$data

  • 实例响应式数据对象。

  • 示例:

    console.log(this.$data) // { count: 0, loading: false }

$props

  • 当前传入的 props 快照。

  • 示例:

    console.log('props snapshot', this.$props)

$el

  • 根 DOM 元素引用。

  • 示例:

    this.$el.classList.add('hydrated')

$options

  • 合并后的组件选项。

  • 示例:

    console.log('component name', this.$options.name)

$parent

  • 父组件实例(谨慎依赖)。

  • 示例:

    this.$parent?.refresh?.()

$root

  • 根组件实例。

  • 示例:

    console.log('root state', this.$root.globalState)

$slots

  • 渲染函数形式的插槽集合。

  • 示例:

    const headerSlot = this.$slots.header?.()

$refs

  • 注册的模板 ref 对象。

  • 示例:

    this.$refs.input.focus()

$attrs

  • 透传 attribute 对象。

  • 示例:

    console.log(this.$attrs)

$watch()

  • 选项式实例方法,行为与组合式 watch 相同。

  • 示例:

    const stop = this.$watch('value', (val, prev) => {
      console.log(val, prev)
    }, { immediate: true })

$emit()

  • 触发自定义事件(支持 payload)。

  • 示例:

    this.$emit('submit', { value: this.value })

$forceUpdate()

  • 强制重新渲染实例,多用于调试。

  • 示例:

    this.$forceUpdate()

$nextTick()

  • 等价于全局 nextTick,以实例为默认 this。

  • 示例:

    await this.$nextTick()
    console.log('dom ready')

内置内容

指令

v-text

  • 直接设置元素 textContent

  • 示例:

    <span v-text="message"></span>

v-html

  • 设置 innerHTML,注意 XSS 风险。

  • 示例:

    <div v-html="trustedHtml"></div>

v-show

  • 通过切换 display 控制显隐。

  • 示例:

    <button v-show="isVisible">Toggle</button>

v-if

  • 条件渲染/卸载子树。

  • 示例:

    <p v-if="loggedIn">Welcome back!</p>
    <p v-else>Guest</p>

v-else

  • 必须紧贴 v-ifv-else-if 使用。

  • 示例:

    <p v-if="count > 0">Positive</p>
    <p v-else>Zero or negative</p>

v-else-if

  • 以链式条件形式配合 v-if

  • 示例:

    <p v-if="score > 90">A</p>
    <p v-else-if="score > 60">B</p>
    <p v-else>C</p>

v-for

  • 遍历渲染列表,需绑定唯一 :key

  • 示例:

    <li v-for="item in items" :key="item.id">{{ item.label }}</li>

v-on

  • 绑定事件监听器,支持修饰符 .stop.prevent 等。

  • 示例:

    <form @submit.prevent="submit">
      <button @click.stop="onClick">Send</button>
    </form>

v-bind

  • 动态绑定 attribute 或 prop,支持对象语法、动态参数。

  • 示例:

    <img v-bind:src="avatarUrl" :alt="user.name">
    <button v-bind="buttonProps">Save</button>

v-model

  • 建立双向绑定,支持修饰符 .lazy.trim.number

  • 示例:

    <input v-model.trim="form.name">
    <CustomInput v-model:number="age" />

v-slot

  • 用于具名/作用域插槽,# 缩写。

  • 示例:

    <Card>
      <template #header>
        <h3>Title</h3>
      </template>
      <template #default="{ item }">
        {{ item.text }}
      </template>
    </Card>

v-pre

  • 跳过该元素及子树的编译。

  • 示例:

    <code v-pre>{{ rawMustache }}</code>

v-once

  • 首次渲染后缓存结果。

  • 示例:

    <p v-once>Compiled once at {{ Date.now() }}</p>

v-memo

  • 缓存子树直至绑定值发生变化,提高性能。

  • 示例:

    <ListView v-memo="[filter, items.length]" />

v-cloak

  • 与 CSS [v-cloak]{display:none} 配合,在编译前隐藏。

  • 示例:

    <div v-cloak>Loading...</div>

组件

<Transition>

  • 为单元素/组件添加进入离开动画,提供事件钩子。

  • 示例:

    <Transition name="fade" @after-enter="onEnter">
      <div v-if="open">Content</div>
    </Transition>

<TransitionGroup>

  • 列表过渡,支持移动过渡与 tag 指定容器。

  • 示例:

    <TransitionGroup tag="ul" name="list">
      <li v-for="item in items" :key="item.id">{{ item.text }}</li>
    </TransitionGroup>

<KeepAlive>

  • 缓存动态组件或路由组件,支持 include/exclude

  • 示例:

    <KeepAlive include="UserList">
      <component :is="activeComponent" />
    </KeepAlive>

<Teleport>

  • 将子树渲染到指定目标节点。

  • 示例:

    <Teleport to="body">
      <Modal v-if="showModal" />
    </Teleport>

<Suspense>

  • 协调异步组件渲染,使用 #fallback 展示占位。

  • 示例:

    <Suspense>
      <AsyncChart />
      <template #fallback>
        <Spinner />
      </template>
    </Suspense>

特殊元素

<component>

  • 动态组件占位符,is 支持组件、标签或异步组件。

  • 示例:

    <component :is="currentTabComponent" />

<slot>

  • 渲染插槽内容,可配合 namefallback

  • 示例:

    <slot name="footer">默认底部</slot>

<template>

  • 包裹多节点或配合指令使用的占位元素,不会渲染为 DOM。

  • 示例:

    <template v-if="items.length">
      <li v-for="item in items" :key="item.id">{{ item.name }}</li>
    </template>

特殊 Attributes

key

  • 标识节点身份,优化 diff。

  • 示例:

    <li v-for="todo in todos" :key="todo.id">{{ todo.title }}</li>

ref

  • 注册模板引用,支持字符串或函数形式。

  • 示例:

    <input ref="input" />

is

  • 在原生元素上挂载自定义组件或保留标签。

  • 示例:

    <button is="my-loading-button">Submit</button>

单文件组件

语法定义

总览

  • .vue 文件由 <template><script><style> 组合,可包含自定义块。

  • 示例:

    <template>
      <h1>{{ title }}</h1>
    </template>
    
    <script>
    export default {
      data: () => ({ title: 'Hello Vue' })
    }
    </script>
    
    <style>
    h1 { color: #42b883; }
    </style>

相应语言块

  • 可声明 lang="ts", lang="scss" 等,交由构建工具处理。

  • 示例:

    <script lang="ts" setup>
    const count: Ref<number> = ref(0)
    </script>
    <style lang="scss">
    .box { color: lighten(#35495e, 10%); }
    </style>

自动名称推导

  • 默认使用文件名作为组件 name

  • 示例:UserList.vue 会自动导出组件名 UserList

预处理器

  • 通过预处理器工具(如 Sass、Pug)转换模板或样式。

  • 示例:

    <template lang="pug">
    h1 Hello
    </template>
    <style lang="sass">
    h1
      color: red
    </style>

src 导入

  • <template src="./foo.html"> 形式复用外部片段。

  • 示例:

    <template src="./header.html"></template>
    <style src="./shared.css"></style>

注释

  • 支持 HTML、JS/TS、CSS 注释,编译器会按块类型处理。

  • 示例:

    <template>
      <!-- 模板注释 -->
      <div>{{ msg }}</div>
    </template>

<script setup>

基本语法

  • 顶层语句即 setup 逻辑,无需显式 return

  • 示例:

    <script setup>
    const count = ref(0)
    const increment = () => count.value++
    </script>

响应式

  • 直接使用组合式 API;顶层声明自动暴露给模板。

  • 示例:

    <script setup>
    const user = reactive({ name: 'Evan' })
    const greeting = computed(() => `Hi ${user.name}`)
    </script>

使用组件

  • 直接导入组件并在模板中使用,无需 components 选项。

  • 示例:

    <script setup>
    import XButton from './XButton.vue'
    </script>
    
    <template>
      <XButton>Click</XButton>
    </template>

使用自定义指令

  • 导入后使用 v-my-directive;可通过 defineExpose 暴露钩子。

  • 示例:

    <script setup>
    import focus from './directives/focus'
    defineExpose({ focus })
    </script>
    
    <template>
      <input v-focus />
    </template>

defineProps() 和 defineEmits()

  • 编译时宏声明 props / emits,自动推导类型。

  • 示例:

    <script setup lang="ts">
    const props = defineProps<{ label: string }>()
    const emit = defineEmits<{
      (e: 'click', value: MouseEvent): void
    }>()
    const onClick = (event: MouseEvent) => emit('click', event)
    </script>

defineModel()

  • Vue 3.5 默认宏,简化多个 v-model 逻辑并支持配置变换。

  • 示例:

    <script setup lang="ts">
    const model = defineModel<number>({ default: 0 })
    </script>

defineExpose()

  • 控制外部可见的实例属性。

  • 示例:

    <script setup>
    const open = () => modal.value?.showModal()
    defineExpose({ open })
    </script>

defineOptions()

  • <script setup> 内设置组件 nameinheritAttrs 等。

  • 示例:

    <script setup>
    defineOptions({ name: 'IconButton', inheritAttrs: false })
    </script>

defineSlots()

  • 声明插槽类型,改善 TS 推断。

  • 示例:

    <script setup lang="ts">
    const slots = defineSlots<{
      default(props: { active: boolean }): any
    }>()
    </script>

useSlots() 和 useAttrs()

  • 组合式辅助,可直接在 <script setup> 使用。

  • 示例:

    <script setup>
    const slots = useSlots()
    const attrs = useAttrs()
    </script>

与普通的 <script> 一起使用

  • 允许同时存在两个 <script>,普通脚本在宏后执行。

  • 示例:

    <script setup>
    const count = ref(0)
    </script>
    <script>
    export default {
      name: 'LegacyCompat'
    }
    </script>

顶层 await

  • 支持 await 用于异步数据获取,Suspense 内自动等待。

  • 示例:

    <script setup>
    const user = await fetchUser()
    </script>

导入语句

  • 顶层导入在编译期提升,支持仅在客户端/服务端导入。

  • 示例:

    <script setup>
    if (import.meta.env.SSR) {
      const { serverOnly } = await import('./server-only')
      serverOnly()
    }
    </script>

泛型

  • 可在 definePropsdefineEmits 等宏中使用 TS 泛型。

  • 示例:

    <script setup lang="ts" generic="T extends string">
    const props = defineProps<{ value: T }>()
    </script>

限制

  • 顶层仅允许声明语句,不支持条件语句包裹组合逻辑。

  • 提示:若需要基于条件导入逻辑,请在函数内部处理或拆分组件。

CSS 功能

组件作用域 CSS

  • 默认通过哈希属性作用域化样式,可配合 :deep():global()

  • 示例:

    <style scoped>
    .title { color: var(--accent); }
    :deep(.child) { margin-top: 1rem; }
    </style>

CSS Modules

  • 通过 module 属性启用,暴露类名映射对象。

  • 示例:

    <template>
      <h1 :class="$style.title">Hello</h1>
    </template>
    <style module>
    .title { color: orange; }
    </style>

CSS 中的 v-bind()

  • 将响应式变量注入到 CSS,自带响应更新。

  • 示例:

    <script setup>
    const primaryColor = ref('#42b883')
    </script>
    <style scoped>
    .badge { background-color: v-bind(primaryColor); }
    </style>

进阶 API

自定义元素

defineCustomElement()

  • 将 Vue 组件转换为原生自定义元素。

  • 示例:

    const MyElement = defineCustomElement({
      props: { msg: String },
      template: `<p>{{ msg }}</p>`
    })
    customElements.define('my-element', MyElement)

useHost()

  • 获取当前自定义元素的宿主元素引用。

  • 示例:

    const host = useHost()
    console.log(host.tagName)

useShadowRoot()

  • 返回自定义元素的 shadow root。

  • 示例:

    const shadow = useShadowRoot()
    shadow?.appendChild(document.createElement('slot'))

this.$host

  • 自定义元素实例上的宿主引用,选项式语法支持。

  • 示例:

    export default {
      methods: {
        logHost() {
          console.log(this.$host)
        }
      }
    }

渲染函数

h()

  • 创建虚拟节点,签名:h(type, props?, children?)

  • 示例:

    return h('button', { class: 'btn', onClick }, slots.default?.())

mergeProps()

  • 合并多个 props 对象,后者覆盖前者。

  • 示例:

    const props = mergeProps({ class: 'btn' }, attrs, { class: 'btn-primary' })

cloneVNode()

  • 克隆 VNode,可指定新的 props / children。

  • 示例:

    const cloned = cloneVNode(vnode, { class: 'highlight' })

isVNode()

  • 判断对象是否为 VNode。

  • 示例:

    console.log(isVNode(child) ? 'vnode' : 'not vnode')

resolveComponent()

  • 在渲染函数中按字符串名称解析已注册组件。

  • 示例:

    const Button = resolveComponent('XButton')
    return h(Button, { onClick })

resolveDirective()

  • 在渲染函数中解析指令定义。

  • 示例:

    const focus = resolveDirective('focus')

withDirectives()

  • 为 VNode 应用一个或多个指令。

  • 示例:

    return withDirectives(h('input'), [[focus]])

withModifiers()

  • 为事件监听函数应用修饰符逻辑(如 stop, prevent)。

  • 示例:

    const onClick = withModifiers(() => emit('click'), ['stop', 'prevent'])

服务端渲染

renderToString()

  • 将应用渲染为完整 HTML 字符串。

  • 示例:

    const html = await renderToString(app)
    response.end(html)

renderToNodeStream()

  • 以 Node.js 流形式输出 HTML。

  • 示例:

    const stream = renderToNodeStream(app)
    stream.pipe(response)

pipeToNodeWritable()

  • 面向 Node Writable 流的现代接口。

  • 示例:

    pipeToNodeWritable(app, response, {
      onReady() {
        response.writeHead(200, { 'content-type': 'text/html' })
      }
    })

renderToWebStream()

  • 返回 Web Streams API 的 ReadableStream

  • 示例:

    const stream = await renderToWebStream(app)
    return new Response(stream, { headers: { 'content-type': 'text/html' } })

pipeToWebWritable()

  • 将 SSR 输出写入 Web WritableStream

  • 示例:

    const body = new WritableStream()
    pipeToWebWritable(app, body)

renderToSimpleStream()

  • 兼容早期实现的简化版流接口。

  • 示例:

    renderToSimpleStream(app, {
      push(chunk) {
        response.write(chunk)
      },
      stop() {
        response.end()
      }
    })

useSSRContext()

  • 在组合式 API 中访问 SSR 上下文(如注入额外状态)。

  • 示例:

    const ctx = useSSRContext()
    ctx.modules.add('src/pages/home.vue')

data-allow-mismatch

  • SSR 特殊 attribute,允许客户端初次渲染与服务端 HTML 不匹配的节点跳过警告,用于第三方控件。

  • 示例:

    <div data-allow-mismatch>
      <!-- 第三方组件输出 -->
    </div>

TypeScript 工具类型

PropType<T>

  • 指定复杂类型的 prop(如联合或函数)。

  • 示例:

    props: {
      validator: {
        type: Function as PropType<(value: string) => boolean>,
        required: true
      }
    }

MaybeRef<T>

  • 表示值可能是 TRef<T>,配合组合式参数使用。

  • 示例:

    function useMaybeRef(input: MaybeRef<number>) {
      return computed(() => unref(input) * 2)
    }

MaybeRefOrGetter<T>

  • 扩展支持 getter 函数,常用于 toValue

  • 示例:

    function useLazy<T>(source: MaybeRefOrGetter<T>) {
      return computed(() => toValue(source))
    }

ExtractPropTypes<T>

  • 根据 props 定义推导出 prop 类型。

  • 示例:

    const propsDef = {
      title: String,
      count: Number
    }
    type Props = ExtractPropTypes<typeof propsDef>

ExtractPublicPropTypes<T>

  • 仅提取可公开访问的 prop 类型。

  • 示例:

    type PublicProps = ExtractPublicPropTypes<typeof propsDef>

ComponentCustomProperties

  • 扩展全局实例属性类型(配合 globalProperties)。

  • 示例:

    declare module 'vue' {
      interface ComponentCustomProperties {
        $t: (key: string) => string
      }
    }

ComponentCustomOptions

  • 扩展组件选项类型。

  • 示例:

    declare module 'vue' {
      interface ComponentCustomOptions {
        analytics?: { event: string }
      }
    }

ComponentCustomProps

  • 扩展全局可用 props(如 Web Components)。

  • 示例:

    declare module 'vue' {
      interface ComponentCustomProps {
        'aria-label'?: string
      }
    }

CSSProperties

  • Vue 内置的行内样式类型定义。

  • 示例:

    const style: CSSProperties = { display: 'flex', gap: '12px' }

自定义渲染

createRenderer()

  • 创建针对自定义平台的渲染器(如原生小程序、桌面端)。

  • 返回 { render, createApp },实现需提供平台特定的节点操作。

  • 示例:

    const { createApp: createCustomApp } = createRenderer({
      createElement: tag => platformCreateElement(tag),
      insert: (el, parent) => parent.appendChild(el),
      patchProp: (el, key, prev, next) => updateProp(el, key, next),
      remove: el => el.remove()
    })

编译时标志

VUE_OPTIONS_API

  • 控制是否包含 Options API,通常由构建工具设置。

  • 示例:

    // vite.config.ts
    export default defineConfig({
      define: {
        __VUE_OPTIONS_API__: true
      }
    })

VUE_PROD_DEVTOOLS

  • 启用后允许在生产环境使用 Vue Devtools。

  • 示例:

    export default defineConfig({
      define: {
        __VUE_PROD_DEVTOOLS__: false
      }
    })

VUE_PROD_HYDRATION_MISMATCH_DETAILS

  • 控制生产环境 Hydration mismatch 警告的详细程度。

  • 示例:

    export default defineConfig({
      define: {
        __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: false
      }
    })

配置指南

  • 编译标志通过打包器 define 注入(如 Vite/Rollup 的 define: { __VUE_OPTIONS_API__: true }),用于 tree-shaking 不需要的功能。

  • 示例:

    export default defineConfig({
      define: {
        __VUE_OPTIONS_API__: false,
        __VUE_PROD_DEVTOOLS__: false
      }
    })

所有 API 均来自 Vue 官方文档 (3.5 系列)。若未来有新增,请以官网更新为准,并同步补充本文档。

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理 邮箱1846861578@qq.com。
技术教程

Python批量扫未注册域名源码

2025-2-6 14:48:50

技术教程

轻松霸榜!免费小米步数代刷/提交服务,日行98800步

2025-11-4 14:27:38

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索