Courses Blog About
⬅️ Back to the course

Basics of reactivity and working with data

reactive

Reactivity in Vue

There are two main ways to create reactive data in Vue 3:

import { ref, reactive } from 'vue'

// For primitives and references
const counter = ref<number>(0)

// For objects and arrays
const user = reactive<{
  name: string
  age: number
}>({
  name: 'Alexander',
  age: 31
})

ref

reactive

It is recommended to always use ref - data will always be available via .value

Practical examples

Counter

<template>
  <div>
    <p>counter: {{ counter }}</p>
    <button @click="increment">+1</button>
  </div>
</template>

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

const counter = ref<number>(0)

const increment = () => {
  counter.value++
}
</script>

User’s Form

<template>
  <form @submit.prevent="saveUser">
    <input v-model="user.name" placeholder="Name">
    <input v-model="user.age" type="number" placeholder="Age">
    <button type="submit">Save</button>
  </form>
</template>

<script setup lang="ts">
import { reactive } from 'vue'

interface User {
  name: string
  age: number | null
}

const user = reactive<User>({
  name: '',
  age: null
})

const saveUser = () => {
  console.log('Saved:', user)
}
</script>

Calculated properties (computed)

For derived data, use computed

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

const price = ref<number>(100)
const discount = ref<number>(10)

const finalPrice = computed<number>(() => {
  return price.value * (1 - discount.value / 100)
})
</script>

<template>
  <p>Final price: {{ finalPrice }}</p>
</template>

Working with arrays

For reactive arrays, use ref

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

interface Todo {
  id: number
  text: string
  done: boolean
}

const todos = ref<Todo[]>([
  { id: 1, text: 'Learn Vue', done: false }
])

const addTodo = (text: string) => {
  todos.value.push({
    id: Date.now(),
    text,
    done: false
  })
}
</script>

Conclusion

Homework assignment: Timer

Create a timer component:

frontline

FrontLine

Join us in telegram

Other interesting posts in a convenient format

Subscribe

Another lessons