The Composition API is a new feature introduced in Vue 3 that provides an alternative syntax for writing component logic. It aims to address the limitations of the Options API, especially when dealing with large components or code reuse. The Composition API allows you to organize and reuse code more effectively.

Key Concepts

  1. Setup Function

The setup function is the entry point of the Composition API. It is called before the component is created and serves as a place to define reactive state, lifecycle hooks, and other logic.

<script>
import { ref } from 'vue';

export default {
  setup() {
    const count = ref(0);

    function increment() {
      count.value++;
    }

    return {
      count,
      increment
    };
  }
};
</script>

  1. Reactive State

Reactive state can be created using ref and reactive functions.

  • ref: Creates a reactive reference to a primitive value.
  • reactive: Creates a reactive object.
import { ref, reactive } from 'vue';

export default {
  setup() {
    const count = ref(0);
    const state = reactive({
      name: 'Vue.js',
      version: 3
    });

    return {
      count,
      state
    };
  }
};

  1. Computed Properties

Computed properties can be created using the computed function.

import { ref, computed } from 'vue';

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

    return {
      count,
      doubleCount
    };
  }
};

  1. Watchers

Watchers can be created using the watch function to perform side effects in response to reactive state changes.

import { ref, watch } from 'vue';

export default {
  setup() {
    const count = ref(0);

    watch(count, (newValue, oldValue) => {
      console.log(`Count changed from ${oldValue} to ${newValue}`);
    });

    return {
      count
    };
  }
};

  1. Lifecycle Hooks

Lifecycle hooks can be used within the setup function using their respective functions.

import { onMounted, onUnmounted } from 'vue';

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

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

    return {};
  }
};

Practical Example

Let's create a simple counter component using the Composition API.

<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment</button>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const count = ref(0);

    function increment() {
      count.value++;
    }

    return {
      count,
      increment
    };
  }
};
</script>

Explanation

  • Template: Displays the count and a button to increment it.
  • Setup Function: Initializes the count state using ref and defines the increment function.
  • Return Object: Exposes count and increment to the template.

Exercise

Create a Vue component using the Composition API that:

  1. Has a reactive state for a list of items.
  2. Allows adding a new item to the list.
  3. Displays the list of items.

Solution

<template>
  <div>
    <input v-model="newItem" placeholder="Add a new item" />
    <button @click="addItem">Add Item</button>
    <ul>
      <li v-for="item in items" :key="item">{{ item }}</li>
    </ul>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  setup() {
    const items = ref([]);
    const newItem = ref('');

    function addItem() {
      if (newItem.value.trim()) {
        items.value.push(newItem.value);
        newItem.value = '';
      }
    }

    return {
      items,
      newItem,
      addItem
    };
  }
};
</script>

Explanation

  • Template: Includes an input field for the new item, a button to add the item, and a list to display the items.
  • Setup Function: Initializes items and newItem using ref, and defines the addItem function.
  • Return Object: Exposes items, newItem, and addItem to the template.

Conclusion

The Composition API in Vue 3 provides a flexible and powerful way to organize and reuse component logic. By using the setup function, reactive state, computed properties, watchers, and lifecycle hooks, you can create more maintainable and scalable Vue applications. This new API is especially useful for large components and complex logic, making your code cleaner and easier to understand.

© Copyright 2024. All rights reserved