Sobes.tech
Middle

What is Composable? Can you give an example of a good composable?

sobes.tech AI

Answer from AI

Composable is a function in Vue 3 (or similar frameworks) that encapsulates and reuses component logic related to state and behavior. Composable allows splitting code into functional blocks, improving readability and maintainability.

A good example of a composable is a function for working with a form that manages field states, validation, and submission:

import { ref } from 'vue';

export function useForm(initialValues) {
  const values = ref({ ...initialValues });
  const errors = ref({});

  function validate() {
    errors.value = {};
    // simple validation: required fields
    for (const key in values.value) {
      if (!values.value[key]) {
        errors.value[key] = 'Field is required';
      }
    }
    return Object.keys(errors.value).length === 0;
  }

  function submit() {
    if (validate()) {
      // submission logic
      console.log('Submitting form', values.value);
    }
  }

  return { values, errors, submit };
}

This composable can be used in different components, reusing the form logic.