shou2017.com
JP

Learning Vue.js Components Through Practical Examples

Wed Nov 7, 2018
Sat Aug 10, 2024

The basics of Vue.js components are explained in detail on the official site, but it can be difficult for beginners to understand.

In particular, I wish there was a bit more explanation about how to actually use components in real application development.

So, I created a Vue.js Component for a real application as an example.

What I Created

I created this simple application. It’s a rather straightforward app that combines a standard Vue.js template with a todo App. While it’s basic, I often found myself confused when applying concepts to real application development, as many other sites only explain todo apps without going further. So I decided to go a step beyond.

This simple Vue.js sample application is ideal for getting familiar with components.

Welcome to Your Vue.js App

todo

Learning Vue.js Components Through Practical Examples

Creating a todos folder

Since all we want to do is display a todo app in a Vue.js template, we’ll create a todos folder to organize all the todo app files.

We only need the files that make up the todo app, so just these four: BaseInputText.vue, TodoListItem.vue, TodoList.vue, and variables.scss.

After completing the above steps, your structure should look like this:

Learning Vue.js Components Through Practical Examples

Displaying the todo app in the Vue template

First, let’s identify which components from the todo app we’ll use in the Vue template.

Looking at the code, it’s easy to see that the todo app is constructed by TodoList.vue importing the BaseInputText.vue and TodoListItem.vue files.

<!-- TodoList.vue -->
import BaseInputText from './BaseInputText.vue'
import TodoListItem from './TodoListItem.vue'

let nextTodoId = 1

export default {
	components: {
		BaseInputText, TodoListItem
	},

So to use the todo app in the Vue template, we only need to import TodoList.vue.

Here’s a simplified diagram:

Learning Vue.js Components Through Practical Examples

And here’s the code:

<!-- App.vue -->

import HelloWorld from "./components/HelloWorld";
import TodoList from "./components/todos/TodoList";

export default {
  name: "App",
  components: {
    HelloWorld, TodoList
  }
};

To display it, we simply add <TodoList/> to the HTML:

<!-- App.vue -->

<template>
  <div id="app">
    <img width="25%" src="./assets/logo.jpg">
    <HelloWorld/>
    <TodoList/>
  </div>
</template>

Here’s the actual implementation:

Sample

Vue.js入門 基礎から実践アプリケーション開発まで

See Also