Vue.js Core Functions

What is a function

A function is an instruction that receives specific data, performs a specified process, and then alters the result.

In Vue.js they can be put in components and should come in handy when creating larger reusable functionality.

Function definition

Last time, I tried to output HelloWorld with the standard output of Vue.js, but this time I will output HelloWorld using a function. Seeing is believing, here’s the code:

<html>
  <head>
    <title>functions</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <div id="app">
    <body>
      <div id="vue\_det" style="text-align: center">
        <h1>{{ greeting() }}</h1>
      </div>
    </body>
  </div>
</html>
<script>
  const { createApp } = Vue;
  createApp({
    data() {
      return {
        message: "Hello World",
      };
    },
    methods: {
      greeting: function () {
        return this message;
      },
    },
  }).mount("#app");
</script>

Save the above code as an HTML file and check it in your browser. It is successful if the following is displayed.

I will explain step by step.

<h1>{{ greeting() }}</h1>

I think that the data defined in Vue.js last time was output with the following code.

<h1>{{ message }}</h1>

This code is the code that executes the function defined in Vue.js. You can execute that function with function name + () and receive the result. Now let’s look at the code below.

methods: {
  greeting: function () {
  return this.message
   }
}

Vue.js creates a methods object when you use a function. This time, in order to create a function for greeting, a function is created with the name greeting. After that, the return statement returns the variable message defined in Vue.js. To refer to variables defined in Vue.js, you must add the this keyword. When illustrated, it looks like the following.

methods: {
Function name: function () {
  return Data to be returned
  }
}

at the end

I think it’s a little difficult, but let’s remember little by little. Code can be downloaded from https://github.com/wiblok/Vue.js