Looking for Vue.js tips and tricks? This ever-growing list of tips and tricks in using Vue.js comes from the day-to-day work as a Vue.js developer. Like some other blog posts on this site, it doesn’t have too much content now, but I’ll keep adding stuff as I stumble upon it in my day-to-day work.

Zoomed-in Vue logo with different colors

1. How do we call a function or a method in the html from the javascript file in vue.js?

This tip is probably going to help people who are just starting to work with Vue.js. It has got to do with mounting a Vue app.

Once we’ve mounted a Vue.js app like shown in the above video, we’ll have the following structure.

In HTML:

1
2
3
<div id="codingexercises">
    {{  thisComesFromVue  }}
</div>

In JS:

1
2
3
4
5
6
new Vue({
    el: "#codingexercises",
    data: {
        thisComesFromVue: "Whatever I want I can add here"
    }
})

Now let’s add a method to be called from HTML.

Let’s list some of the ways of doing it:

  1. Use a Vue-powered event handler in HTML (with variable assignment right in the v-on directive)
  2. Use a Vue-powered event handler in HTML (with variable assignment in the methods option)
  3. Using computed option on our Vue instance
  4. Hook into one of Vue’s lifecycle hooks

We’ll cover only the first two ways from the above list.

In the case of using an event handler, we’d update our HTML to this:

1
2
3
4
5
<div id="codingexercises">
  <p v-on:click="thisComesFromVue = 'asdf'" >
    {{  thisComesFromVue  }}
  </p>
</div>

Next, we’d update our JS to this:

1
2
3
4
5
6
new Vue({
    el: "#codingexercises",
    data: {
        thisComesFromVue: "Whatever I want I can add here",
    },
});

This first scenario can be found on Codepen, and is an example of assigning to a new variable value right in the v-on directive.

The second scenario is somewhat similar to the first one, and can be found in another dedicated codepen.

In this second case, the HTML looks like this:

1
2
3
4
5
<div id="codingexercises">
  <p v-on:click="clickHandler()" >
    {{  thisComesFromVue  }}
  </p>
</div>

…and the JS looks like this:

1
2
3
4
5
6
7
8
9
10
11
new Vue({
    el: "#codingexercises",
    data: {
        thisComesFromVue: "Whatever I want I can add here",
    },
    methods: {
      clickHandler() {
        this.thisComesFromVue = "asdf";
      },
    },
});

While there are other ways to do this, the first two options are good enough for beginners to understand how to invoke, from html, a method defined in a Vue instance.

2. To be continued…