Vue Methods

Vue Methods

When your Vue application requires complex logic, you should extract that code into reusable functions.

In Vue, these functions are called "Methods".

Methods are declared inside the methods object of your Vue application instance.


Declaring Methods

To declare methods, you add a methods property to your component configuration.

This property expects an object containing your custom functions.

Once defined, these methods can be called directly from your HTML templates.

Declaring a Method:

const app = Vue.createApp({
  data() {
    return { count: 0 }
  },
  methods: {
    increment() {
      this.count++;
    }
  }
});

Accessing Data with 'this'

Notice the use of the this keyword in the example above.

Inside a Vue method, this automatically points to the current component instance.

You must use this to access or modify any variables defined in your data() function!

Using 'this' in Methods:

<button @click="changeText">Click Me</button>

Passing Arguments to Methods

You can easily pass arguments to your methods directly from the HTML template.

This allows you to reuse a single method for different buttons or inputs.

Passing Arguments Example:

<button @click="say('Hello')">Say Hello</button>
<button @click="say('Goodbye')">Say Goodbye</button>

Exercise 1 of 1

?

How do you properly access a variable named 'username' (which is defined in data) from inside a Vue method?