Blog>
Snippets

Using Refs for Reactive Properties

Explain the usage of refs for primitive data types to create reactive properties in the Vue.js 3 Composition API.
<template>
  <div>
    <input v-model="message" type="text" placeholder="Type a message">
    <p>You typed: {{ message }}</p>
  </div>
</template>

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

export default {
  setup() {
    // Declare a reactive reference 'message'
    const message = ref('');

    // Return the reactive reference to use it in the template
    return { message };
  }
};
</script>
This is a Vue 3 component using the Composition API. It includes an input element bound to a reactive ref called 'message'. The paragraph element displays the current value of 'message'. When the input changes, the message ref is automatically updated to reflect the changes because of Vue's reactivity system.
<style>
  div {
    margin: 10px;
  }
  input {
    padding: 8px;
    margin-bottom: 4px;
    border: 1px solid #ccc;
    border-radius: 4px;
  }
  p {
    color: #666;
  }
</style>
This CSS provides simple styling for the Vue component. It targets the div, input, and paragraph elements within the component, giving them some padding, margin, borders, and color. This will improve the visual presentation of the example in a browser.