阿里云主机折上折
  • 微信号
Current Site:Index > Changes in Vue 3 component registration

Changes in Vue 3 component registration

Author:Chuan Chen 阅读数:21359人阅读 分类: Vue.js

Vue 3 has introduced multiple improvements in component registration, including adjustments to global registration, local registration, and asynchronous components, along with new changes brought by the Composition API. Below is a detailed analysis of these changes from different perspectives.

Changes in Global Component Registration

In Vue 3, the global component registration method has shifted from Vue.component() to app.component(), adapting to the new way of creating application instances. After creating an application instance, all global components are mounted to that instance:

// Vue 2 syntax
Vue.component('my-component', {
  /* options */
})

// Vue 3 syntax
const app = Vue.createApp({})
app.component('my-component', {
  /* options */
})

This change allows multiple Vue applications to coexist without interfering with each other. For example, running two independent applications on the same page:

const app1 = Vue.createApp({})
app1.component('comp-a', { /* ... */ })

const app2 = Vue.createApp({})
app2.component('comp-b', { /* ... */ })

// Components from the two applications do not interfere with each other

Improvements in Local Component Registration

The syntax for local component registration remains similar, but the Composition API offers more flexible usage. Vue 3 allows components to be used directly in setup():

// Options API
const app = Vue.createApp({
  components: {
    'component-a': ComponentA,
    'component-b': ComponentB
  }
})

// Composition API
import ComponentA from './ComponentA.vue'
import ComponentB from './ComponentB.vue'

export default {
  setup() {
    return {}
  },
  components: {
    ComponentA,
    ComponentB
  }
}

In Single-File Components (SFCs), Vue 3 also supports a more concise local registration approach:

<script setup>
import ComponentA from './ComponentA.vue'
</script>

<template>
  <ComponentA />
</template>

New Syntax for Asynchronous Components

Vue 3 revamped the API for asynchronous components, introducing the defineAsyncComponent method:

// Vue 2 syntax
const AsyncComponent = () => ({
  component: import('./MyComponent.vue'),
  loading: LoadingComponent,
  error: ErrorComponent,
  delay: 200,
  timeout: 3000
})

// Vue 3 syntax
import { defineAsyncComponent } from 'vue'

const AsyncComponent = defineAsyncComponent({
  loader: () => import('./MyComponent.vue'),
  loadingComponent: LoadingComponent,
  errorComponent: ErrorComponent,
  delay: 200,
  timeout: 3000,
  suspensible: false
})

The new API provides clearer configuration naming and adds the suspensible option to control whether it works with the <Suspense> component.

Changes in Component Naming Conventions

Vue 3 recommends using PascalCase for component names, aligning with most modern frontend toolchains:

// Recommended
app.component('MyComponent', {
  /* ... */
})

// Still supported but not recommended
app.component('my-component', {
  /* ... */
})

In templates, both naming conventions work:

<template>
  <MyComponent />
  <my-component />
</template>

Adjustments to Dynamic Components

In Vue 3, the usage of the is attribute for dynamic components has been adjusted to clearly distinguish between dynamic components and native HTML elements:

<!-- In Vue 2, it could be used directly -->
<component :is="currentComponent" />

<!-- In Vue 3, a prefix is required for distinction -->
<component :is="currentComponent" /> <!-- Component -->
<component is="div" /> <!-- Native element -->

For reserved elements (e.g., children of table), the v-is directive is required:

<table>
  <tr v-is="'my-row-component'"></tr>
</table>

Changes to Functional Components

In Vue 3, functional components must be explicitly defined as functions, and the functional option is no longer supported:

// Vue 2 syntax
Vue.component('functional-comp', {
  functional: true,
  render(h, context) {
    return h('div', context.props.msg)
  }
})

// Vue 3 syntax
import { h } from 'vue'

const FunctionalComp = (props, context) => {
  return h('div', props.msg)
}

Upgrades to Component v-model

Vue 3 introduces significant improvements to v-model, supporting multiple v-model bindings and custom modifiers:

<ChildComponent v-model:title="pageTitle" v-model:content="pageContent" />

<!-- Equivalent to -->
<ChildComponent
  :title="pageTitle"
  @update:title="pageTitle = $event"
  :content="pageContent"
  @update:content="pageContent = $event"
/>

Internal handling in the component:

export default {
  props: ['title', 'content'],
  emits: ['update:title', 'update:content'],
  setup(props, { emit }) {
    const updateTitle = (newVal) => {
      emit('update:title', newVal)
    }
    
    const updateContent = (newVal) => {
      emit('update:content', newVal)
    }
    
    return { updateTitle, updateContent }
  }
}

Improvements in Custom Element Interaction

Vue 3 provides a clearer way to handle custom elements (Web Components):

const app = Vue.createApp({
  compilerOptions: {
    isCustomElement: tag => tag.includes('-')
  }
})

With this configuration, all tag names containing hyphens will be treated as custom elements and not parsed as Vue components.

Adjustments to Component Inheritance

Vue 3 removes $listeners and the .native modifier, unifying event handling with v-on:

<!-- In Vue 2, .native was needed for native events -->
<my-component @click.native="handleClick" />

<!-- In Vue 3, unified handling -->
<my-component @click="handleClick" />

Components must declare emitted events via the emits option:

export default {
  emits: ['click'],
  setup(props, { emit }) {
    const handleInternalClick = () => {
      emit('click', payload)
    }
    
    return { handleInternalClick }
  }
}

Changes to Component Instance Properties

Certain properties of component instances have changed in Vue 3, requiring special attention:

// Vue 2
this.$children // Access child components
this.$scopedSlots // Access scoped slots

// Vue 3
setup(props, { slots, attrs, emit }) {
  // Accessed via context parameters
}

Handling of Recursive Components

In Vue 3, recursive components must be explicitly named and cannot rely on filenames:

// Must be named
export default {
  name: 'RecursiveComponent',
  setup() {
    // ...
  }
}

Optimizations for Scoped Component Styles

Vue 3 improves the implementation of scoped styles using a new PostCSS approach:

<style scoped>
/* More efficient attribute selectors are generated */
.example {
  color: red;
}
</style>

Enhanced Component Type Support

For TypeScript projects, Vue 3 offers better component type support:

import { defineComponent } from 'vue'

export default defineComponent({
  name: 'TypeSafeComponent',
  props: {
    message: {
      type: String,
      required: true
    }
  },
  setup(props) {
    props.message // Type inferred as string
  }
})

Performance Optimizations for Components

Vue 3's component registration mechanism includes performance optimizations:

  1. Global component registration no longer affects all application instances.
  2. Local component registration performs more static analysis during compilation.
  3. Functional components have significantly lower creation overhead.
// Example of a performance-optimized functional component
import { defineComponent } from 'vue'

const OptimizedComponent = defineComponent(() => {
  // Lightweight render function
  return () => h('div', 'Hello')
})

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.