Blog>
Snippets

Reactivity in the Composition API

Create a simple component that uses the Composition API to demonstrate a piece of state's lifecycle from reactive declaration to usage in the template.
<template>
  <div>
    <h1>{{ message }}</h1>
    <button @click="updateMessage">Change Message</button>
  </div>
</template>
This is the HTML template for our Vue component. It displays a message and has a button that when clicked will trigger `updateMessage` method to change the message.
<script setup>
import { ref } from 'vue';

// Create a reactive state variable
const message = ref('Hello World!');

// Function to update the message
function updateMessage() {
  message.value = 'Hello Vue 3!';
}
</script>
Here we have a Vue component script using the Composition API. We import `ref` from Vue, which allows us to create a reactive reference. `message` is our reactive state. The `updateMessage` function is an example of changing the reactive state.
<style scoped>
h1 {
  color: blue;
}
button {
  background-color: yellow;
  border: none;
  padding: 10px 20px;
  cursor: pointer;
}
</style>
These are the scoped CSS styles for our component. The `<style scoped>` tag ensures that styles are applied only to this component. The `h1` tag is styled to have blue text and the `button` has a yellow background with some padding.