Blog>
Snippets

Using the Reactive Composition API

Implement a feature with Vue 3's Composition API that utilizes ref, reactive, and computed properties to manage complex state reactivity.
<template>
  <div>
    <p>First name: {{ fullName.firstName }}</p>
    <p>Last name: {{ fullName.lastName }}</p>
    <p>Full name: {{ computedFullName }}</p>

    <input v-model="userInput.firstName" placeholder="Enter first name">
    <input v-model="userInput.lastName" placeholder="Enter last name">
  </div>
</template>
This defines the structure of the Vue component in HTML. It renders the first name, last name, and full name. There are input fields for the user to type in the first and last names.
<script setup>
import { ref, reactive, computed } from 'vue';

const userInput = reactive({
  firstName: '',
  lastName: ''
});

const fullName = computed(() => ({
  firstName: userInput.firstName,
  lastName: userInput.lastName
}));

const computedFullName = computed(() => `${fullName.value.firstName} ${fullName.value.lastName}`.trim());
</script>
This JavaScript code imports reactive utilities from Vue and creates a reactive state object for user input and computed properties to handle the full name logic.
<style scoped>
div {
  margin: 20px;
}

p {
  font-size: 16px;
  margin-bottom: 10px;
}

input {
  margin: 10px 0;
  padding: 8px;
  font-size: 14px;
}
</style>
CSS styles scoped to the component to add basic styling to the div, paragraph elements, and input fields.