Introduction to Vue.js: Building Components with the standalone version

Posted by


Vue.js is a popular JavaScript framework for building user interfaces and single page applications. It offers a simple and flexible approach to building interactive web applications, and one of its key features is the ability to create reusable components.

In this tutorial, we will guide you through the process of creating components using the standalone version of Vue.js. The standalone version can be included directly in your HTML file without the need for a build system or module bundler like Webpack or Babel.

Step 1: Include Vue.js in your HTML file
The first step is to include the Vue.js library in your HTML file. You can download the standalone version from the official Vue.js website, or use a CDN link. Here’s an example of how to include Vue.js in your HTML file:

<!DOCTYPE html>
<html>
<head>
  <title>Vue.js 101: Creating Components</title>
  <script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
</head>
<body>
  <!-- Your content here -->
</body>
</html>

Step 2: Create a Vue instance
Next, you need to create a Vue instance in your HTML file. This is done by using the new Vue() constructor function and passing an object with some configuration options. Here’s an example of how to create a Vue instance:

<script>
new Vue({
  el: '#app',
  data: {
    message: 'Hello, Vue!',
  }
});
</script>

In this example, we are creating a Vue instance with an element selector #app and a data object with a message property. The message property will be used to display a message in our component.

Step 3: Create a Vue component
Now that we have our Vue instance set up, we can create a Vue component. Components are reusable Vue instances that can be used to encapsulate functionality and structure your application. Here’s an example of how to create a simple component:

<script>
Vue.component('hello-world', {
  template: '<div>{{ message }}</div>',
  data: function() {
    return {
      message: 'Hello, World!',
    }
  }
});
</script>

In this example, we are creating a component called hello-world with a template property that contains our HTML template. The data function returns an object with a message property that will be displayed in the component.

Step 4: Use the Vue component
To use our newly created Vue component, we need to add it to our HTML file within the Vue instance element. Here’s an example of how to use the hello-world component:

<body>
  <div id="app">
    <hello-world></hello-world>
  </div>
</body>

In this example, we are adding the hello-world component inside the #app element of our Vue instance. When you open the HTML file in a browser, you should see the message "Hello, World!" displayed on the screen.

That’s it! You have successfully created a Vue component using the standalone version of Vue.js. You can continue to create more components and build more complex applications using Vue.js. Happy coding!