Methods & Directives in VueJS

Checkout the previous Components and Single File Components in Vue in this series.

The starter app is, unsurprisingly,  dull but we can make it interesting by adding some methods and event listeners. Component methods are defined in the methods property of a Vue instance, and in single-file components this also lives in the <script> section. Defined methods are bound and available to the template section. They act like standard Javascript methods to mutate data and react to interactions performed on the rendered DOM.

Methods (and data) can be glued to the DOM via directives which are attributes added to templates that allow components to listen to events emitted by the DOM and Vue. These typically take the form of v-on:click or v-on:<event> (Vue also has helpful @  short forms, @click, for these) and embedded into HTML. For example:

<button v-on:click="onClickFunction()">Click Me</button>

Directives can also enable conditional (v-if) or iterative (v-for) logic that allows you to render components under certain circumstances or multiple times. Let's add a button to the default template and a method to increment a count value stored in data in the HelloWorld.vue component

<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <p> {{count}}</p>
    <button v-on:click="increment()"> 
      Count + 1
    </button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data() {
    return {
      count: 0
    }
  },
  methods: {
    increment() {
      this.$data.count +=1 
    }
  }
}
</script>

Vue is full of these directives, features and functions and we will see more of as you work through it, but those should be enough basics to get you started!