Blog>
Snippets

Basic Reactive Counter Example

Showcase Vue 3's reactivity system by building a simple counter that updates the DOM in response to state changes.
<div id="app">
  <h1>{{ counter }}</h1>
  <button @click="counter++">Increment</button>
</div>
This is the HTML structure providing a header displaying the counter and a button to increment it. The Vue.js template syntax is used to display and update the counter in the DOM.
<script src="https://unpkg.com/vue@next"></script>
<script>
const { createApp, ref } = Vue;

createApp({
  setup() {
    // Declares a reactive state variable `counter`
    const counter = ref(0);

    // makes `counter` available to the template
    return { counter };
  }
}).mount('#app');
</script>
This is the JavaScript code including Vue.js script via CDN and creating a new Vue application with a reactive state `counter` using the Composition API, where `ref` is a function to make the variable reactive. The `counter` reactive variable is incremented when the button is clicked.
<style>
#app {
  text-align: center;
  margin-top: 50px;
}

button {
  font-size: 20px;
  padding: 10px 20px;
}
</style>
This is the CSS styling for the Vue app and button, centering the content and applying basic styling to the button.