Day 3 of 10 day Vue Js challenge
We have 7 days remaining to complete our challenge, let us get the ball rolling.
1. Computed properties in vue
In Vue, computed properties are special reactive values that automatically recalculate when their dependencies change and are cached until then. In your code, the computed property codesantara depends on name and returns its uppercase version. This means whenever you type in the input field bound to name, Vue will automatically update codesantara and display the uppercase string in the template. The important difference from using a plain function is that a computed property is cached and only re-evaluated when its dependent reactive values (like name.value) change, whereas a normal function inside the template would run every time the component re-renders, even if name hasn’t changed. This makes computed properties more efficient and declarative for deriving new values from existing state.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
<title>Computed properties</title>
</head>
<body>
<div id="app">
<p>Computed properties </p>
<input type="text" v-model.trim="name">
{{codesantara}}
</div>
</body>
<script>
const { createApp, ref, computed } = Vue;
createApp({
setup() {
let name = ref("10 day vue challenge");
codesantara = computed(()=>{
return name.value.toUpperCase();
});
return {
name,
codesantara
};
},
}).mount("#app")
</script>
</html>