0Pricing
Frontend Academy · Lesson

The setup() Function and script setup

Write logic in the setup() function or use the sugar, expose values to the template, and understand lifecycle hooks in Composition API.

The setup() Function

In Vue 3's Composition API, setup() is a component option that replaces data, methods, computed, and watch. It receives props and the setup context as arguments and returns what the template needs.

export default {
  props: { userId: String },
  setup(props, { emit, attrs, slots }) {
    const user = ref(null);
    onMounted(async () => {
      user.value = await fetchUser(props.userId);
    });
    return { user }; // must return what template uses
  }
};

<script setup> — Syntax Sugar

<script setup> is compile-time syntax sugar for setup(). Everything declared at the top level is automatically available in the template. No return statement needed.

<script setup lang="ts">
import { ref, onMounted } from 'vue';

const count = ref(0);
// count is automatically available in template
</script>

All lessons in this course

  1. ref() and reactive()
  2. computed() and watch()
  3. The setup() Function and script setup
  4. Composables: Reusable Composition Functions
← Back to Frontend Academy