<template>
<div>
<p>Original Price: {{ price }}</p>
<p>Discounted Price: {{ discountedPrice }}</p>
<button @click="increasePrice">Increase Price</button>
</div>
</template>
<script>
export default {
data() {
return {
price: 100,
discount: 20
};
},
computed: {
discountedPrice() {
return this.price - this.discount;
}
},
methods: {
increasePrice() {
this.price += 10;
}
}
};
</script>
discountedPrice
is automatically updated whenever price
changes.watch
)watch
in Vue.js (Options API)<template>
<div>
<p>Search Query: {{ query }}</p>
<input v-model="query" placeholder="Type something..." />
</div>
</template>
<script>
export default {
data() {
return {
query: ""
};
},
watch: {
query(newVal) {
console.log("User searched:", newVal);
}
}
};
</script>
query
value updates.watch
function logs the new query value every time it changes.In Vue 3, computed and watch are used inside the setup()
function.
<template>
<div>
<p>Count: {{ count }}</p>
<p>Double Count: {{ doubleCount }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { ref, computed } from "vue";
export default {
setup() {
const count = ref(0);
const doubleCount = computed(() => count.value * 2);
const increment = () => {
count.value++;
};
return { count, doubleCount, increment };
}
};
</script>
Example: Watcher in Composition API
<template>
<div>
<p>Temperature: {{ temperature }}°C</p>
<button @click="increaseTemp">Increase Temperature</button>
</div>
</template>
<script>
import { ref, watch } from "vue";
export default {
setup() {
const temperature = ref(20);
watch(temperature, (newVal, oldVal) => {
console.log(`Temperature changed from ${oldVal}°C to ${newVal}°C`);
});
const increaseTemp = () => {
temperature.value++;
};
return { temperature, increaseTemp };
}
};
</script>
Feature | Computed Properties | Watchers |
---|---|---|
Use Case | When deriving new values from existing state | When reacting to state changes (e.g., API calls) |
Performance | Cached for efficiency | Executes function every time data changes |
Example | Formatting a date, calculating totals | Watching form inputs, tracking changes over time |
computed()
and watch()
inside setup()
.Mastering these concepts will help you build efficient and reactive Vue.js applications. 🚀