Creating a Hello World Program in Vue.js: A Beginner’s Tutorial

Rumman Ansari   Software Engineer   2024-07-19 03:30:20   5670  Share
Subject Syllabus DetailsSubject Details
☰ TContent
☰Fullscreen

Table of Content:

The Formal Start
  • In this topic, you will understand the difference between a dynamic web-page and a static web-page.

  • For this, you will build a minimalistic HTML and JS code to display Hello World! on the browser, without Vue.

  • After that, Vue code will be added (using CDN) and tested using browser developer console to test the dynamic nature of the web-page.

HTML and JS

Vue JS works by binding JS with HTML and optionally with CSS. Consider the sample HTML and JS code without Vue part in it, as given below. After that, to understand the difference, Vue will be added.


<!-- index.html -->
 
<h1>Loading...</h1>
 


// main.js
var message = "Hello World!";
window.onload = function() {
    document.querySelector('h1').innerHTML = message;
};

Output without Vue
Vue JS
Adding the magic

Now add the magic potion from Vue JS and check how the JS variables can be used in HTML.

The magic requires to include the Vue JS file from it's CDN.


<!-- index.html -->
<html>
 
    <script src="https://unpkg.com/vue"></script>
 
    <div id="vueMain">
      <h1>{{ message }}</h1>
  </div>
 </html>


// main.js
var app = null;
window.onload = function() {
  app = new Vue({
    el: '#vueMain',
    data: { message: 'Hello World!' }
  });
};

Note: Do not use the body tag's ID to refer to root element.

Testing the Power of magic
Vue JS
Revealing the Secret of magic
  • Vue instance is the root of the application.

  • It is created by specifying various options to store data and perform actions.

  • Vue instance is plugged into the el attribute forming a relationship between the instance and the portion of HTML element.

  • The 'data' attribute allows you to access the variables for that instance.

Note: In the first example without Vue, execute message = "Hi All!" in the developer console. The HTML will not get updated.

A Visual Explanation

The given image explains how JS data is being used in HTML files.