</>
Skip to content
Vue lessons (20/43)

Vue — Composition API

setup function

<script>
import { ref, computed } from 'vue'

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

    function increment() {
      count.value++
    }

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

script setup (recommended)

<script setup>
import { ref, computed } from 'vue'

const count = ref(0)
const doubleCount = computed(() => count.value * 2)

function increment() {
  count.value++
}
</script>

reactive objects

<script setup>
import { reactive } from 'vue'

const state = reactive({
  count: 0,
  user: { name: 'John', age: 25 }
})

function increment() {
  state.count++
}
</script>

refs vs reactive

<script setup>
import { ref, reactive } from 'vue'

// Use ref for primitives
const count = ref(0)
const name = ref('John')

// Use reactive for objects
const user = reactive({ name: 'John', age: 25 })
</script>

computed

<script setup>
import { ref, computed } from 'vue'

const firstName = ref('John')
const lastName = ref('Doe')

const fullName = computed(() => {
  return `${firstName.value} ${lastName.value}`
})
</script>

watch and watchEffect

<script setup>
import { ref, watch, watchEffect } from 'vue'

const count = ref(0)

watch(count, (newVal, oldVal) => {
  console.log(`Changed from ${oldVal} to ${newVal}`)
})

watchEffect(() => {
  console.log(`Count is: ${count.value}`)
})
</script>

Lifecycle hooks

<script setup>
import { onMounted, onUnmounted } from 'vue'

onMounted(() => {
  console.log('Mounted!')
})

onUnmounted(() => {
  console.log('Unmounted!')
})
</script>

Mini Practice

  1. Rewrite a component with script setup
  2. Use ref and reactive
  3. Add computed and watch
  4. Use lifecycle hooks

Up Next

Continue with Script Setup - Syntax sugar.

Related Topics

Frequently Asked Questions about Composition API

What is Composition API in Vue?

Composition API is a fundamental concept in Vue. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Composition API?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Composition API.

Why is Composition API important in Vue?

Composition API is essential for Vue development. Understanding this concept will help you write better code and solve real-world problems more effectively.