Vue.js
Beginner
1 min read
Computed Properties Basics
Example
<script setup>
import { ref, computed } from 'vue';
const firstName = ref('Jane');
const lastName = ref('Doe');
const cart = ref([
{ name: 'Widget', price: 9.99, qty: 2 },
{ name: 'Gadget', price: 24.99, qty: 1 }
]);
// ── Read-only computed ─────────────────────────
const fullName = computed(() => `${firstName.value} ${lastName.value}`);
const cartTotal = computed(() =>
cart.value.reduce((sum, item) => sum + item.price * item.qty, 0)
);
const cartSummary = computed(() =>
`${cart.value.length} item(s) — $${cartTotal.value.toFixed(2)}`
);
// ── Writable computed ─────────────────────────
const fullNameRW = computed({
get: () => `${firstName.value} ${lastName.value}`,
set: (val) => {
const [first, ...rest] = val.split(' ');
firstName.value = first;
lastName.value = rest.join(' ');
}
});
// Setting fullNameRW updates both refs:
fullNameRW.value = 'John Smith';
</script>
<template>
<p>{{ fullName }}</p>
<p>{{ cartSummary }}</p>
</template>