JAVASCRIPT

Efficient Computed Properties with Getters/Setters in Vue 3

Learn to create powerful Vue 3 computed properties with both a getter and a setter, enabling two-way data binding and derived state manipulation effectively.

<script setup>
import { ref, computed } from 'vue';

const firstName = ref('John');
const lastName = ref('Doe');

const fullName = computed({
  get() {
    return firstName.value + ' ' + lastName.value;
  },
  set(newValue) {
    const names = newValue.split(' ');
    firstName.value = names[0] || '';
    lastName.value = names[1] || '';
  }
});

// Example usage
// Accessing the computed value
console.log(fullName.value); // John Doe

// Setting the computed value (triggers setter)
fullName.value = 'Jane Smith';
console.log(firstName.value); // Jane
console.log(lastName.value);  // Smith
</script>

<template>
  <div>
    <p>First Name: {{ firstName }}</p>
    <p>Last Name: {{ lastName }}</p>
    <p>Full Name: {{ fullName }}</p>
    <input v-model="fullName" placeholder="Edit Full Name" />
  </div>
</template>
How it works: This snippet demonstrates how to define a computed property with both a `get` and `set` function. The `get` function returns the derived value (e.g., `fullName` from `firstName` and `lastName`). The `set` function allows you to assign a new value to the computed property, which then updates its dependent reactive sources. This enables powerful two-way data binding for complex derived states, similar to how `v-model` works internally, making your components more flexible and reactive.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs