Vue.js / Vue Composition API

Composing Logic with setup() Function

This tutorial focuses on the setup() function, the entry point for using the Composition API. You will learn how to compose the logic of your Vue components using this function.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Explores Vue 3's Composition API for structuring applications.

Composing Logic with setup() Function: A Vue.js Tutorial

Introduction

In this tutorial, we will focus on the setup() function in Vue.js, a crucial part of the Composition API. The setup() function is the entry point for using the Composition API, which allows you to organize your component's logic in a more intuitive and flexible way.

By the end of this tutorial, you will learn how to use and compose the logic of your Vue components using the setup() function.

Prerequisites: Basic understanding of JavaScript and Vue.js.

Step-by-Step Guide

The setup() function is where you define all the reactive data, computed properties, functions, and lifecycle hooks of your component when using the Composition API.

The setup() function

The setup() function is a new component option in Vue.js 3. It serves as the entry point for using the Composition API within your Vue components.

Here's an example of a very basic setup() function:

export default {
  setup() {
    // component logic here
  }
}

Reactive Data

To create reactive data, you use the reactive() or ref() functions within setup().

import { reactive } from 'vue'

export default {
  setup() {
    const state = reactive({
      count: 0,
    })
    return { state }
  }
}

In this example, state is a reactive object with a count property.

Code Examples

Example 1: Using setup() with a method

import { ref } from 'vue'

export default {
  setup() {
    const count = ref(0)
    const increment = () => {
      count.value++
    }

    return { count, increment }
  }
}

In this example, count is a reactive reference to the number 0, and increment is a method that increases count by one. These are then returned from setup() so they can be used in the template.

Example 2: Using setup() with a computed property

import { ref, computed } from 'vue'

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

    return { count, double }
  }
}

In this example, double is a computed property that's always twice the value of count.

Summary

We've covered how to use the setup() function to create a component's reactive data and methods, and how to return these to make them available in the template. Your next step could be to learn about lifecycle hooks in the Composition API, or how to extract and reuse logic between components.

Practice Exercises

  1. Create a Vue component with reactive data and a method using setup().
  2. Add a computed property to your component that depends on the reactive data.
  3. Refactor a component from the Options API to use the setup() function instead.

Here's a solution for exercise 1:

import { ref } from 'vue'

export default {
  setup() {
    const name = ref('Vue')
    const greet = () => {
      console.log(`Hello, ${name.value}!`)
    }

    return { name, greet }
  }
}

In this example, name is a reactive reference to the string 'Vue', and greet is a method that logs a greeting to the console. These are then returned from setup() so they can be used in the template.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

MD5/SHA Hash Generator

Generate MD5, SHA-1, SHA-256, or SHA-512 hashes.

Use tool

Favicon Generator

Create favicons from images.

Use tool

PDF Password Protector

Add or remove passwords from PDF files.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

Backlink Checker

Analyze and validate backlinks.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help