Vue Js Methods – Demystified

Unraveling the intricacies of Vue.js methods is essential for mastering the framework. This article demystifies Vue.js methods, exploring the 'what' of their functionality, the 'who' in terms of developers leveraging these methods, and the 'why' behind their significance in creating dynamic and interactive web applications with Vue.js. Gain a comprehensive understanding to enhance your proficiency in Vue.js development.

We talk again about Vue JS because most app development companies still prefer this flexible, progressive Java Script framework to build the user interface. Vue JS is open-source and one of the most adaptable web technologies, so it became the go-to framework for web app development, especially for single-page applications that run javascript. It currently has 198k stars on GitHub.

As user experience becomes one of the main differentiators for digital products, the better the front-end developers work, the more satisfied users. So let’s dive into the secrets of Vue software development and uncover what Vue Js Methods are all about.

1. What are Vue Js methods?

When building the UI, components are time and nerve saviors, as they allow us to reuse pieces and think of them separately while organizing the app into a tree of components. Here, we talk about a Vue component model that encapsulates logic and customized content in each component.

Now, what are the Vue methods? They are objects associated with a Vue instance. Otherwise, vue js methods are functions that trigger certain actions as commanded by the user. They are commonly used for event handling. A method named by the key of the object returns an object.

You can work with method handlers when you want to listen to DOM events and an inline event handler is not enough due to complexity. You can call a component’s method path or name by employing the v-on directive.

2. How do I define a method in Vue component?

You can define methods either inside the method property or in Single File components. Here’s how:

  1. inside the method property: new Vue({ methods: { // add your function associated to event
  2. in Single File Components: < script > export default { methods: { // add the function associated to event

To access data from Vue JS methods, just use this.property name.

3. What is the difference between a computed property and methods in Vue Js?

We all agree that VueJS provides many advantages. But when learning Vue Js, the difference between vuejs methods and computed is one of the first puzzling things associated with Vue. Although they are very similar, there are also important differences that can clarify which one to use and when.

Arguments

Methods accept arguments, while a computed property doesn’t. That is why Vue JS methods are so versatile. You can even apply a method call within another method. Methods are often defined to display an output (such as the number of active users) by just clicking the button assigned to that function.

A computed property, while not accepting arguments, fetches data from existing sources and uses it to compose new data, resulting in dynamic values based on data properties. To use the same example, compared to the use of methods, computed property allows displaying the number of active users without clicking a button.

Caching

A computed property is cached, which implies that, for accessing data, the function runs just once if the value remains unchanged. On the other hand, methods need to run data property checks every time because they cannot tell otherwise if the values are changed inside the method property. Whenever a render happens, the method is called and will run the function. So, when choosing methods or computed properties, think about what benefits you need to get from the Vue JS function render.

Vue js methods are useful to call functions for event handling in the DOM, to call a vue js function component when there is a change, or to pass parameters. Computed properties are the better choice to set up new data from existing sources, reference values directly in a template (no additional action needed), or for repeated vue js calling function when clicking the button.

4. What does data() do in Vue?

Another dilemma is the Vue JS function or methods’ object. When writing data: function (), we talk about Vue.JS function data, which enables each instance to maintain a returned data object copy independently. So we use data() to declare a component’s reactive state.

Reusable components are one of the advantages the VueJS provides. To make the most of it, you should use data: function() {return { … };} or data() {return { … };}.

By declaring it a function, Vue calls it when it creates a new component instance. The returned object is wrapped in its reactivity system. As a result, the object’s top-level properties are proxied to the component instance.

It is the Vue JS call method of child component individual instances, for which all the data you operate on defined inside a unique object. You use data() so that the same data object is not shared between other child components, which can lead to bugs.

5. How do you call a method in computed Vue?

Sometimes, you may need to call vue methods components outside those components. Speaking of Vue JS 2 methods, you can call components in three ways, according to the Vue JS good practices (or development course):

  1. Event Bus

We’re talking about a Vue instance that emits events defined inside one component, followed by listening and reacting to that event in a different component. You can implement event buses as instance properties or as an ES6 module.

For the instance property, to make it globally available for all components, you can use:

import Vue from 'vue';
Vue.prototype.$eventBus = new Vue();

So, when you write this.$eventBus, it becomes accessible anywhere in the app.

The ES6 module’s principle is similar: create a variable that you export so it becomes available anywhere in the app. For that, first, you create a new file in the project named event-bus.js. Then, in the same file, add

import Vue from 'vue';
const EventBus = new Vue();
export default EventBus;

This is how you create the ES6 module. To import it to the components, where you want to use it, all you have to do is to import:

< script >
import EventBus from './event-bus.js'
export default {
...
}
< /script >

Now, to emit an event in a component, write:

< script >
export default {
methods: {
callMethodInChildComponent() {
//As an instance property
this.$eventBus.$emit("callMethodInChild");
//As an ES6 module.
EventBus.$emit("callMethodInChild");
},
},
};
< /script >

Finally, the vue js call method on component:

< script >
export default {
mounted() {
//As an instance property
this.$eventBus.$on("callMethodInChild", () => {
this.methodInChild();
});
//As an ES6 module
EventBus.$on("callMethodInChild", () => {
this.methodInChild();
});
},
methods: {
methodInChild() {
//Execute code
},
},
};
< /script >
  1. $refs

This approach is also applicable for calling Vue JS 3 methods object when a method is called from outside the component. It is handy for the Vue JS call method from parent component. You’ll use the ref attribute to attach a reference ID to a child component.

To see more clearly how the Vue JS trigger method in child component works, let’s take the example of displaying the “Hello world” message when the Greet button is clicked:

< template >
< HelloWorld ref="helloWorld" />
<button @click="greet">greet< /button>
< /template >

You can now access the Vue JS call method of the child component. To call it from the parent component directly, write:

< script >
import HelloWorld from "./components/HelloWorld";
export default {
name: "App",
components: {
HelloWorld,
},
methods: {
greet() {
this.$refs.helloWorld.greet("alex");
},
},
};
< /script >

The helloWorld ref was assigned to the helloWorld component. The greet method was added to call the this.$refs.helloWorld.greet method. So, when Alex is logged in and clicks the Greet button, a Hello World Alex message should be displayed.

  1. $emit

This is another approach also available for calling both Vue JS 2 methods and Vue JS 3 methods. What it does is to emit (as the property name simply says) custom events from child components. As a result, those custom events can be listened to from the parent components.

There is one detail to which you need to be careful: the emitted event’s name must be the same as the one used for listening that event.

So, in our Hello World example, you would have:

< script >
export default {
methods: {
greet() {
this.$emit("greet", "alex");
},
},
};
< /script >

In this case, the Vue JS call method from parent component greet. It calls the event with this.$emit followed by the name of the event and the event payload.

To listen to the greet event in the parent component:

< template >
< div >hello world < /div >
<button @click="greet">greet< /button>

In short, for vue js call method from parent component in child, assign ref to the component. The other way around – call from the child in the parent component, emit an event in child and listen to it in the parent component.

Image from undraw.co

6. What is the difference between watch and computed in Vuejs?

Next to Vue JS methods, computed properties and watchers are another two important concepts. We’ve already checked the vue js methods vs computed, now let us see how computed and watch are different.

First, to understand each of them:

A computed property is a property used to manipulate already existing data. So, its value is evaluated each time dependency changes. You can use it for form validation.

A watcher is a function. It is automatically executed by Vue JS when there is a change in the property that is watched. So, a watcher tracks certain properties, runs the function, and fetches data when those properties change. Generally, watchers allow, on a Vue instance, to observe and then react to data changes.

Now let’s understand what each of them does because it is here where the differences lie.

Computed properties are usually employed for sorting through large data groups when you don’t want to rerun calculations redundantly, but only when there is a change. For instance, you can use computed to filter a large list while the user is typing. You can also use computed for form validation or visualize data that changes according to what the users want to see.

Computed properties are reactive and update only when needed, as they are cached based on dependencies. They need to be pure functions and synchronous, as they cannot change anything, just return the new value.

Watchers are a better choice for listening and calling function when there is a change in a specific property (and only when the change happens). Also, you’d better use them for more complex executions, such as asynchronous operations or HTTP calls, which could not be performed with computed properties.

To sum up, computed properties are to be used to calculate new values based on other existing properties; the property is reevaluated each time automatically there is a change in the dependency, so you don’t need to watch each of those dependencies. On the other hand, use watchers for more generic operations such as HTTP calls, setting timers, or storing data in local storage.

7. Are Vue methods reactive?

First, let’s understand what „reactive” means in our context. In Vue JS, reactivity refers to the automatic rendering in the DOM of any changes in the application. We talk about using Vue for reactive user interfaces and about its reactive architecture. But when going in-depth into the JS code, are all its elements reactive?

In short, methods are not reactive. They can, however, contain reactive references. Changing one of those references triggers re-rendering in the template if it uses the method (which gets re-called).

We use the data option to declare a component’s reactive state, whose value is a function that returns an object. To make it “reactive,” Vue converts its properties into getter/setters.

In Vue 2 JS code, use object.defineProperty to set the getters and the setters. Vue JS 3 comes with a new reactive system that utilizes the proxies of JavaScript. With the help of proxy objects, you can create proxies for other objects, which you can intercept and then redefine some fundamental operations for them, like get and set, to see which data is accessed and changed.

8. Vue Js methods examples

Some of the most common use cases for a method in VueJS are actions performed when clicking a button or entering data in a text input.

For a click event, let’s take the example of the message “Hello. Nice to see you.” when a button is clicked.

First, create the method:

< script >
export default {
methods: {
handleClick() {
alert('Hello. Nice to see you.');
},
handleInput() {
console.log('Text input changed');
},
},
};
< /script >

Now, for event handlers, we use a v-on directive that is attached to an element:

< template >
< div >
< button v-on:click="handleClick">Click me< /button >
< input v-on:input="handleInput" / >
< /div >
< /template >< script >
export default {
methods: {
handleClick() {
alert('Hello. Nice to see you.');
},
handleInput() {
console.log('Text input changed');
},
},
};
< /script >

Instead of v-on: you can also use @.

Another example is to use a method in VueJS to increase the total in a shopping cart on an online platform, for instance.

Let’s say we have an Add to cart button. Following

< div class="products">
< button>Add to cart< /button>
< /div>

a click event was emitted in the DOM. Next, we use the v-on directive to get Vue to respond to the click event. To define the event that needs to be handled, provide an argument – click sounds the most logical in our example. So, what needs to happen when the user clicks the Add to cart button? Let’s say that the total amount increases by 5. For this, we need to assign the directive with an expression: total += 5. In consequence, the total value of the property will increase by 5. When applying methods, it is imperative to use this in the script file.

By using methods, it should look like this:

methods: {
addToCart() {
this.total += 5;
}
}

What this does is make accessible the context object that was bound to all the functions.

The “magic” that should happen is automatically updating the total (and the page) by simply clicking a button. You’ve probably experienced it many times while shopping online when the number of items in the shopping cart is updated automatically. The most probable reason is that the app was developed by using Vue JS and, in particular, with the help of VueJS methods.

If you are unsure that Vue JS is a good choice, check our analysis for Vue vs Angular and Vue vs React to see if the other web technologies could prove better suited.

Related post

Upcoming resource:
Pre-register to get early access to a comprehensive audit and in-depth analysis of a dozen HCP portals across Europe.
Marketing Specialist

Blending technology with creativity, Teodora turns cups of coffee into carefully written thoughts. With the power of the Oxford comma and a bit of magic, she brings words closer to people.

hello@digitalya.co

Articles
Browse more related content

#Development Tools

Laravel Validation – The Step-by-Step Guide

#Development Tools

Vue vs Angular – A comprehensive comparison

#Development Tools

PHP vs Node — a head to head comparison

#Healthcare

AI in Pharma Compliance — Navigating the Complex Landscape

#Healthcare

AI-powered social listening — identifying key opinion leaders in pharma

#Healthcare

Internal AI chatbots for pharma — streamlining internal processes

Do you want to develop a product?

Send us your idea. We usually reply in just a few hours.