Methods in Vue.js are the functions declared inside the Vue.js component’s `methods` object. By managing and encapsulating logic, they improve the modularity and maintainability of your component.
Declaring the Methods
Methods are declared inside the `methods` object of a Vue component. They can be called using other methods or straight from the template.
<template>
<div>
<p>Message: {{ message}}</p>
<button @click="updateMessage">Update message</button>
</div>
</template>
<script>
export default {
data() {
return {
message: "Welcome to my blog."
};
},
methods: {
updateMessage() {
this.message="Welcome to Medium";
}
}
};
</script>
In this example, clicking the "Update message" button causes the `updateMessage` method to be called, which updates the `message` property.
Method calling from the templates
Methods can be directly called from the templates using the text interpolation `{{ method() }}` syntax. This is very useful to display dynamic content.
<template>
<div>
{{ greetingsMessage() }}
</div>
</template>
<script>
export default {
methods: {
greetingsMessage() {
return 'Welcome to Medium!';
}
}
};
</script>