Blog>
Snippets

Basic Reactive Counter Component

Create a simple counter component that reacts to button clicks, demonstrating Vue's reactivity system.
<div id='counter-app'>
  <p>{{ counter }}</p>
  <button v-on:click='incrementCounter'>Increment</button>
</div>
HTML markup for the Vue app. It includes a paragraph element that will display the current counter value and a button to increment the counter.
<script src='https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.min.js'></script>
<script>
  new Vue({
    el: '#counter-app',
    data: {
      counter: 0
    },
    methods: {
      incrementCounter: function() {
        this.counter += 1;
      }
    }
  });
</script>
JavaScript code using Vue.js. It includes the data property for reactive state (counter) and a method (incrementCounter) to increment the counter. Vue's reactivity system ensures the DOM updates when the counter changes.
<style>
  #counter-app { text-align: center; }
  #counter-app p { font-size: 24px; }
  #counter-app button { margin-top: 10px; }
</style>
CSS styles for the counter app. It centers the text, sets the font size for the counter display, and adds margin above the button.