0
0
Vueframework~30 mins

Computed with getter and setter in Vue - Mini Project: Build & Apply

Choose your learning style9 modes available
Computed Property with Getter and Setter in Vue
📖 Scenario: You are building a simple Vue component that manages a user's full name. The full name is made by combining first and last names. You want to show the full name and also allow editing it in one input box.
🎯 Goal: Create a Vue component that uses a computed property with a getter and setter to combine firstName and lastName into fullName. When the user edits fullName, it should update firstName and lastName accordingly.
📋 What You'll Learn
Create reactive variables firstName and lastName with initial values
Create a computed property called fullName with a getter that returns the combined name
Add a setter to fullName that splits the input and updates firstName and lastName
Bind fullName to an input box in the template for two-way editing
💡 Why This Matters
🌍 Real World
This pattern is useful when you want to combine multiple pieces of data into one editable field, like full names, addresses, or formatted dates.
💼 Career
Understanding computed properties with getters and setters is essential for building reactive and user-friendly Vue applications, a common requirement in frontend development roles.
Progress0 / 4 steps
1
Setup reactive firstName and lastName
In the <script setup> section, create two reactive variables called firstName and lastName using Vue's ref. Set firstName to "John" and lastName to "Doe".
Vue
Hint

Use import { ref } from 'vue' and then const firstName = ref('John') and const lastName = ref('Doe').

2
Create computed fullName with getter
Import computed from Vue. Create a computed property called fullName with a getter that returns the combined string of firstName.value and lastName.value separated by a space.
Vue
Hint

Use computed(() => `${firstName.value} ${lastName.value}`) to create the getter.

3
Add setter to fullName computed property
Modify the fullName computed property to have a setter function. The setter should take a string, split it by space into two parts, and update firstName.value and lastName.value accordingly. Use the computed function with an object containing get and set.
Vue
Hint

Use computed({ get() { ... }, set(value) { ... } }) and split the input string.

4
Bind fullName to input in template
In the <template>, add an <input> element. Bind its v-model to the computed property fullName so that editing the input updates firstName and lastName.
Vue
Hint

Use <input v-model="fullName" /> to bind the input to the computed property.