Lists, Conditionals and Lifecycle

Harry · 14 Sep 2026 · 1 views
Advertisement
Advertisement

Conditional rendering

v-if adds or removes elements from the DOM; v-show just toggles CSS visibility (cheaper for frequent toggles):

<p v-if="loggedIn">Welcome back</p>
<p v-else>Please sign in</p>

<div v-show="isOpen">Panel</div>

Rendering lists

v-for repeats an element for each item. Always give a stable :key so Vue can update the list efficiently:

<ul>
  <li v-for="item in items" :key="item.id">
    {{ item.name }}
  </li>
</ul>

Lifecycle hooks

Components pass through a lifecycle – created, mounted to the DOM, updated, and unmounted. You hook into these moments to run code such as fetching data:

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

const users = ref([])

onMounted(async () => {
  users.value = await fetch('/api/users').then(r => r.json())
})

onUnmounted(() => {
  // clean up timers, listeners
})
</script>

onMounted is the usual place to load initial data, because the component is now in the DOM.

The bigger ecosystem

  • Vue Router – client-side navigation between pages.
  • Pinia – shared state management across components.
  • Vite – the build tool that powers development and production builds.

Key points

  • v-if/v-else add and remove elements; v-show toggles visibility.
  • v-for renders lists – always provide a stable :key.
  • Lifecycle hooks like onMounted run code at key moments (e.g. fetch data).
  • Vue Router, Pinia and Vite round out a full application.
Share this post:

Comments (0)

Please login or register to comment.