<template>
<div>
<p>{{ message }}</p>
<button @click="updateMessage">Click me</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const message = ref('Hello')
function updateMessage() {
message.value = 'Hello Vue!'
}
</script>The template uses Vue's reactive ref to store message. Initially, it shows 'Hello'. When the button is clicked, the updateMessage function changes message.value to 'Hello Vue!'. Vue automatically updates the displayed text.
isVisible is true.v-if completely removes or adds the element based on the condition.v-if conditionally renders the element only if the expression is true. v-show toggles visibility but keeps the element in the DOM. v-else-if is used after v-if or v-else. v-for is for loops, not conditions.
<template>
<ul>
<li v-for="item in items" :key="item.id">{{ item.name }}</li>
</ul>
<button @click="addItem">Add Item</button>
</template>
<script setup>
import { reactive } from 'vue'
const items = reactive([{ id: 1, name: 'Apple' }, { id: 2, name: 'Banana' }])
function addItem() {
items.push({ id: 3, name: 'Cherry' })
}
</script>Vue's reactive does not track array mutations like push properly. Using ref for arrays is recommended to ensure reactivity on mutations.
Vue templates allow the framework to track data changes and update only the parts of the DOM that need changing. This makes code simpler and faster compared to manual DOM updates.
<template>
<div>
<p>{{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script setup>
import { ref } from 'vue'
const count = ref(0)
function increment() {
count.value += 1
if (count.value === 2) {
count.value = 10
}
}
</script>On first click, count goes from 0 to 1. On second click, count goes from 1 to 2, triggering the condition that sets count to 10. So the displayed number after two clicks is 10.