Component API

On this page 17

The Component API is the core building block of stx applications. This guide covers all aspects of component creation and lifecycle management.

Component Definition

Basic Component

export default {
  name: 'MyComponent',
  props: {
    message: String,
    count: {
      type: Number,
      default: 0
    }
  },
  setup(props) {
    // Component logic here
  }
}

Composition API

import { ref, computed } from 'stx'

export default {
  setup() {
    const count = ref(0)
    const doubled = computed(() => count.value * 2)

    return {
      count,
      doubled
    }
  }
}

Component Properties

Props

props: {
  title: String,
  likes: Number,
  isPublished: Boolean,
  commentIds: Array,
  author: Object,
  callback: Function,
  contactsPromise: Promise
}

Computed Properties

const fullName = computed(() => {
  return firstName.value + ' ' + lastName.value
})

Methods

function increment() {
  count.value++
}

Lifecycle Hooks

import { onMounted, onUpdated, onUnmounted } from 'stx'

export default {
  setup() {
    onMounted(() => {
      console.log('Component mounted')
    })

    onUpdated(() => {
      console.log('Component updated')
    })

    onUnmounted(() => {
      console.log('Component unmounted')
    })
  }
}

Component Communication

Events

// Emitting events
const emit = defineEmits(['change', 'update'])
emit('change', newValue)

// Listening to events
<MyComponent @change="handleChange" />

Provide/Inject

// In parent
provide('key', value)

// In child
const injectedValue = inject('key')

Component Patterns

Composables

// useCounter.ts
export function useCounter() {
  const count = ref(0)
  const increment = () => count.value++
  const decrement = () => count.value--

  return {
    count,
    increment,
    decrement
  }
}

// Component usage
const { count, increment } = useCounter()

Slots

<template>
  <div class="container">
    <slot>Default content</slot>
    <slot name="footer"></slot>
  </div>
</template>

Best Practices

  1. Use TypeScript for better type safety
  2. Keep components focused and single-responsibility
  3. Use composables for reusable logic
  4. Properly type props and events
  5. Document component APIs

TypeScript Integration

interface Props {
  message: string
  count?: number
}

defineProps<Props>()