Blog>
Snippets

Creating a reactive counter with Vue 3's Composition API

Demonstrate how to use the reactive state and handle user interactions to implement a counter.
<div id="app">
  <h1>{{ counter }}</h1>
  <button @click="increment">Increment</button>
  <button @click="decrement">Decrement</button>
</div>
This is the HTML structure with Vue directives. It displays the counter value and two buttons to increment and decrement the counter.
const { createApp, reactive } = Vue;

createApp({
  setup() {
    const state = reactive({
      counter: 0
    });

    function increment() {
      state.counter++;
    }

    function decrement() {
      state.counter--;
    }

    return {
      ...toRefs(state),
      increment,
      decrement
    };
  }
}).mount('#app');
This JavaScript code uses Vue 3's Composition API to create a reactive state object for the counter and defines increment and decrement functions to modify it. The `toRefs` function is used to return a reactive reference for the template to use.
#app {
  text-align: center;
  margin-top: 50px;
}

button {
  margin: 5px;
  padding: 10px 20px;
  font-size: 16px;
}
The CSS styles for the application. It aligns the text to the center, provides some margin to the top, and styles the buttons with margin, padding, and font-size.