In Vue.js, methods play a crucial role in handling actions and events associated with a Vue instance. They are essentially functions that are defined inside the methods property. In this blog, we will explore the concept of Vue.js methods and understand how they work.

What are Vue.js methods?

A Vue method is a function that is associated with a Vue instance. These methods are defined inside the methods property, which allows you to encapsulate and organize your code.

Here is an example of defining a method in a Vue instance:

new Vue({
 methods: {
 handleClick: function() {
 alert('test');
 }
 }
})

Similarly, for Single File Components, you can define methods as follows:

<script>
export default {
 methods: {
 handleClick: function() {
 alert('test');
 }
 }
}
</script>

Methods are especially useful when you need to perform an action and attach a v-on directive to handle events. For instance, you can have an element that triggers the handleClick method when clicked:

<template>
 <a @click="handleClick">Click me!</a>
</template>

Passing parameters to Vue.js methods

Vue methods can also accept parameters. To pass a parameter to a method, you simply pass it in the template where the method is called:

<template>
 <a @click="handleClick('something')">Click me!</a>
</template>

Here is an example of defining a method that accepts a parameter in a Vue instance:

new Vue({
 methods: {
 handleClick: function(text) {
 alert(text);
 }
 }
})

For Single File Components, you can define methods with parameters like this:

<script>
export default {
 methods: {
 handleClick: function(text) {
 alert(text);
 }
 }
}
</script>

Accessing data from a method

Within a Vue method, you can access any of the data properties of the Vue component using this.propertyName. This provides an easy way to access and modify data.

Consider the following example:

<template>
 <a @click="handleClick">Click me!</a>
</template>

<script>
export default {
 data() {
 return {
 name: 'Flavio'
 }
 },
 methods: {
 handleClick: function() {
 console.log(this.name);
 }
 }
}
</script>

In this case, we are logging the value of name to the console when the handleClick method is called.

It’s important to note that you don’t have to use this.data.name, instead, you can simply use this.name. Vue provides a transparent binding for accessing data properties. Using this.data.name will raise an error.

Methods are closely linked to events, as they are commonly used as event handlers. Whenever an event occurs, the associated method is called to handle the event.

In conclusion, Vue.js methods are an essential aspect of building interactive and dynamic Vue applications. They allow you to encapsulate logic, handle events, and interact with data. By understanding how to define and use methods effectively, you can create powerful Vue components.