Vue3 Composition API Declaration

Benefits of composition api

  • Code sharing
  • Module-level state management
  • Better code organization, and a clear indication of code source
  • Better handling of duplicate function and variable names compared to mixin
  • Eliminate dependency on Vuex or Pinia, learn 1 technique instead of 4 (Vuex, Pinia, mixin, Composition API), and gain the same feature capabilities

Setup Examples:

// e.g. /apps/src/components/MyComponent.vue
import useComposable from './useComposable.js'

// ❌ Avoid this pattern
setup() {
  return {
    ...useComposable(),
  }
},

// ❌ Avoid this pattern
setup() {
  const {
    state,
    computed1,
    computed2,
    method1,
    method2
  } = useComposable()

  return {
    state,
    computed1,
    computed2,
    method1,
    method2
  }
},

// ✅ Use this pattern
setup() {
  return {
    composable: useComposable(),
  }
},

Reasons:

  • Although the first pattern is simple, when data variables, methods, or computed fields are used, it is difficult to tell where they come from
  • The second pattern shows source, but it involves a lot of unnecessary code
  • The third pattern is the best of both worlds, usage involves the key (e.g. composable.method())
Share: