Introduction to Vue 3 Composition API: Setup, Reactive State Management, and Lifecycle Hooks

The Composition API introduces a flexible approach to writing Vue components.

setup() Function

The setup() function is the entry point for Composition API logic, executed before the component is created:

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

export default {
  setup() {
    const message = ref('Hello, Vue 3!');
    return { message };
  },
};
</script>

Reactive State Management

Use ref() or reactive() for state:

import { reactive } from 'vue';

export default {
  setup() {
    const state = reactive({ count: 0 });
    const increment = () => state.count++;
    return { state, increment };
  },
};

Lifecycle Hooks

Lifecycle hooks like onMounted replace component options:

import { onMounted } from 'vue';

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

Leave a comment

Your email address will not be published. Required fields are marked *