Blog>
Snippets

Combining ref with reactive for mixed-state management

Demonstrate how to combine 'ref' and 'reactive' in the same component to manage a combination of scalar and complex state reactively.
<template>
  <div>
    <input v-model="user.name" placeholder="Enter your name" />
    <input v-model.number="age" placeholder="Enter your age" />
    <p>{{ user.name }}, age {{ age }}</p>
  </div>
</template>

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

export default {
  setup() {
    // 'ref' is used to create a reactive reference for a scalar value
    const age = ref(0);

    // 'reactive' is used to define a reactive state for a complex object
    const user = reactive({
      name: '',
    });

    // Return both states to be used in the template
    return {
      age,
      user,
    };
  }
};
</script>

<style>
div {
  margin: 20px;
}
</style>
This Vue component demonstrates combining 'ref' with 'reactive' for mixed-state management. The 'ref' is used for scalar 'age' state while 'reactive' is used for a complex 'user' state with a 'name' property. The user's name and age are bound to input fields and display reactively.