John Daly

Writing Better Components in Vue

John Daly


This article was originally published on the Mesh Blog

When starting a new project, you want to get things up and running as quickly as possible. While modern JavaScript advancements have made things a lot easier on developers, they have also increased the complexity of getting things going. Every developer who has worked with Webpack knows what I am talking about; Webpack is a great example of a very powerful tool that has an incredibly steep learning curve, even for doing basic things. Fortunately there is a solution for those who want to go fast: Vue and vue-cli.

I don’t think I have come across a solution that so easily gets you up and on your way to developing a modern JavaScript web application. The vue-cli frees you from the tedious initial Webpack configuration, and allows you to start writing application code right away. While this is great, I have found there to be some shortcomings to Vue itself; mainly that Vue code can be very messy and cluttered. Here is what the standard format for a .vue file looks like:

1<template>2  <!-- HTML goes here -->3</template>4
5<script>6  // JavaScript goes here7</script>8
9<style>10  /* CSS goes Here */11</style>

The HTML, JavaScript, and CSS are all located in one single file. While this is okay for small components, and you could argue that it promotes keeping things simple and breaking big components into many smaller components, I find that it can easily result in monolithic files which are hard to read and difficult for others to maintain.

I also find that this style is the most commonly used way to write Vue code, being used in official examples and in most Vue projects I have come across. Honestly, this would prove to be a potential deal breaker for me if I was deciding between using React or Vue for a larger web app. Fortunately though, there is a way to separate the three pieces of the .vue file into their own files, leading to code that is easier to read and maintain.

The source code for this project can be found here.

Lets Build a Vue App

To see how easy vue-cli makes things for us, lets start from scratch:

1. Download the vue-cli

npm install -g @vue/cli

2. Create your project with vue-cli

vue init webpack <project-name-here>

This command will lead you through a step-by-step process to configure your project. Here is what I selected for this project:

? Project name readable-vue-components? Project description A Vue.js project? Author John Daly <my email here>? Vue build standalone? Install vue-router? Yes? Use ESLint to lint your code? Yes? Pick an ESLint preset Standard? Set up unit tests Yes? Pick a test runner jest? Setup e2e tests with Nightwatch? No? Should we run `npm install` for you after the project has been created? (recommended) npm

Congratulations, you have successfully set up your project! One last thing before we start building components, we are going to install Buefy, a great UI package for Vue:

3. Install Buefy

npm install --save-dev buefy

4. Adding Buefy to the Project

Go into src/main.js and add the following imports:

1import Buefy from 'buefy';2import 'buefy/lib/buefy.css';

Next configure Vue to use Buefy:


Your main.js file should now look like this:

1// The Vue build version to load with the `import` command2// (runtime-only or standalone) has been set in webpack.base.conf with an alias.3import Vue from 'vue';4import Buefy from 'buefy';5import App from './App';6import router from './router';7import 'buefy/lib/buefy.css';8
11Vue.config.productionTip = false;12
13/* eslint-disable no-new */14new Vue({15  el: '#app',16  router,17  components: { App },18  template: '<App/>',19});

5. Update the Router

Go into src/router/index.js and update it to look as follows:

1import Vue from 'vue';2import Router from 'vue-router';3import CheckList from '@/components/Checklist/Checklist';4
7export default new Router({8  routes: [9    {10      path: '/',11      name: 'Checklist',12      component: Checklist,13    },14  ],15});

We are now ready to start building the Checklist and ChecklistItem components!

Building the Components

We will be building a simple todo list app, which will have the following functionality:

  1. Add items to the list
  2. Remove items from the list
  3. Edit items on the list
  4. Check off items on the list

Checklist Component

Let’s start by adding a new folder to hold our components. Create a folder called Checklist in src/components and put the following files inside of it:

  1. Checklist.vue
  2. template.html
  3. script.js
  4. style.css

Next, we will hook up the template, script, and style files in the Checklist file:

1<template src="./template.html" />2<script src="./script.js" />3<style src="./style.css" />

Now we can focus on the individual pieces that make up the .vue file, rather than having them all crammed in the same file!

Building the Template

Lets open up our src/components/Checklist/template.html file and get started.

Here is what we are going to want our Checklist to look like:

<--      Header       --><--  New Item Input   --><--                   --><--  Checklist Items  -->

We can quickly tackle these piece by piece:


This will be simple, just a standard <h1> title:


New Item Input

Next we want a text input, with a button to confirm the value:

1<b-field>2  <b-input v-model="newItem" expanded @keyup.native.enter="addItem" />3  <p class="control">4    <button class="button is-primary" @click="addItem">Add</button>5  </p>6</b-field>7
8<!-- We want a divider to be rendered if we have any items in the Checklist -->9<hr v-show="checklistItems.length > 0" />

Checklist Items

Finally, we want the Checklist to be filled with ChecklistItem components. We will be building this component later, but we will add this here now.

1<ChecklistItem2  v-for="item in checklistItems"3  :key="item.key"4  :itemTitle="item.title"5  :indexKey="item.key"6/>

Finished Template

To wrap up this template, we will put each of those pieces in the following set of divs:

1<div class="container is-fluid">2  <div class="section">3    <div class="checklist-box">4      <!-- Header -->5      <!-- New Item Input -->6      <!-- Checklist Items -->7    </div>8  </div>9</div>

Your template file should now look like this:

1<div class="container is-fluid">2  <div class="section">3    <div class="checklist-box">4      <!-- Header -->5      <h1>Checklist</h1>6
7      <!-- New Item Input -->8      <b-field>9        <b-input v-model="newItem" expanded @keyup.native.enter="addItem" />10        <p class="control">11          <button class="button is-primary" @click="addItem">Add</button>12        </p>13      </b-field>14
15      <hr v-show="checklistItems.length > 0" />16
17      <!-- Checklist Items -->18      <ChecklistItem19        v-for="item in checklistItems"20        :key="item.key"21        :itemTitle="item.title"22        :indexKey="item.key"23      />24    </div>25  </div>26</div>

Writing the Script

Next, we will open up our JavaScript file at src/components/Checklist/script.js.


The name of the component will be Checklist:

1const name = 'Checklist';


The Checklist component is going to render many ChecklistItem components as new items are added. We need to import the ChecklistItem component and register it as a component of Checklist:

1// Put this at top of file2import ChecklistItem from './ChecklistItem/ChecklistItem';3
4const components = {5  ChecklistItem,6};


We won't need any props for this component


According to our template, we will only need two properties in our data object: - The description of a new item to add (newItem) - A list, holding properties of the ChecklistItem components that will be in the Checklist

1const data = function () {2  return {3    checklistItems: [],4    newItem: '',5  };6};


The methods we will need for this component are simple add/deleteItem operations


addItem will create a new object, which holds information that will be used by the ChecklistItem component, and push it into the checklistItems list.

1const addItem = function () {2  let key = 0;3  const numItems = this.checklistItems.length;4  if (numItems !== 0) {5    // In an effort to keep the key of an item unique in the6    // set we will set the new item's key to be equal to the7    // latest item's key, plus 18    key = this.checklistItems[numItems - 1].key + 1;9  }10
11  // Add the newItem information to the checklistItems list12  this.checklistItems.push({ key, title: this.newItem });13
14  // Reset the newItem value15  this.newItem = '';16};

deleteItem will take a key, and will remove the entry from checklistItems that has that key.

1const deleteItem = function (indexKey) {2  // Loop through the checklistItems list3  for (let i = 0; i < this.checklistItems.length; i++) {4    // Check the current element to see if we have a key match5    if (this.checklistItems[i].key === indexKey) {6      // Splice the matching element out of the7      // list and break from the loop8      this.checklistItems.splice(i, 1);9      break;10    }11  }12};
Exporting the script

With the script logic written, we need to export it in the same way you export in a standard Vue file:

1export default {2  name,3  components,4  props: {},5  data,6  computed: {},7  methods: {8    addItem,9    deleteItem,10  },11};

Finishing the Script

Here is what the finished script file should look like:

1import ChecklistItem from './ChecklistItem/ChecklistItem';2
3// ==================4// NAME5// ==================6const name = 'Checklist';7
8// ==================9// COMPONENTS10// ==================11const components = {12  ChecklistItem,13};14
15// ==================16// PROPS17// ==================18const props = {};19
20// ================21// DATA22// ================23const data = function () {24  return {25    checklistItems: [],26    newItem: '',27  };28};29
30// ================31// COMPUTED32// ================33const computed = {};34
35// =================36// METHODS37// =================38
39/**40 * Creates a new item from the value of newItem41 * and pushes it into the checklistItems list42 */43const addItem = function () {44  let key = 0;45  if (this.checklistItems.length !== 0) {46    key = this.checklistItems[this.checklistItems.length - 1].key + 1;47  }48  this.checklistItems.push({ key, title: this.newItem });49  this.newItem = '';50};51
52/**53 * Removes the item with the given indexKey from the checklistItems list54 * @param indexKey Number the key of the item to remove55 */56const deleteItem = function (indexKey) {57  for (let i = 0; i < this.checklistItems.length; i++) {58    if (this.checklistItems[i].key === indexKey) {59      this.checklistItems.splice(i, 1);60      break;61    }62  }63};64
65export default {66  name,67  components,68  props,69  data,70  computed,71  methods: {72    addItem,73    deleteItem,74  },75};

Writing the CSS

Finally we will add some styling for our component with the src/components/Checklist/style.css file.

Our styling for this component is going to be simple, we want it to be held in a div that is centered, has a rounded border, a bit of box-shadow, and some padding:

1.checklist-box {2  margin-left: auto;3  margin-right: auto;4  width: 85%;5  border-radius: 5px;6  border: 1px solid #e7eaec;7  box-shadow: 0px 0px 4px rgba(134, 134, 134, 0.21);8  padding: 15px 15px 15px 15px;9}

ChecklistItem Component

The ChecklistItem component will be the individual listings that appear within the Checklist. We will start by creating a new folder ChecklistItem within our existing Checklist folder. As before, we will add the following 4 files:

  1. ChecklistItem.vue
  2. template.html
  3. script.js
  4. style.css

Matching the way we made the Checklist component, the ChecklistItem.vue file will look like this:

1<template src="./template.html" />2<script src="./script.js" />3<style src="./style.css" />

Building the Template

First, open the template file located at src/components/Checklist/ChecklistItem/template.html.

For our template, we want an item to look like this:

+----------------------------------+|[ ] [   <Item Description>   ] [X]|+----------------------------------+ (A)            (B)             (C)

Here is a breakdown of what makes up this component:

A) Checkbox to mark an item as being finished B) Text field that includes a description of the item, it will be possible for user’s to edit this field C) Button to remove the item from the Checklist

Item Finished Checkbox

We just need a simple checkbox that is bound to a data value of the component:

1<b-checkbox v-model="itemChecked" />

Item Description Text

This will be a text span that will hold the description of the item:

1<span2  class="item-static"3  :class="{'item-checked': itemChecked}"4  v-show="!editingItem"5  @dblclick="editItem"6>7  {{itemTitleDone}}8</span>

A few things to take note of here:

  • We are conditionally adding a class called item-checked if the value of itemChecked is true
  • We are only rendering this text span if editingItem is false; aka don’t show this text if the item is being edited
  • When the text span is double clicked, we are calling the editItem function

Edit Item Description Input

We will need a way to allow for an item’s text to be edited, for that we will add a text input field:

1<!-- Edit Item Description Input -->2<b-input3  v-model="itemTitleEdit"4  v-show="editingItem"5  :disabled="itemChecked"6  @blur="doneEdit"7  @keyup.native.enter="doneEdit"8  @keyup.native.esc="cancelEdit"9  expanded10/>

Things to note:

  • We only show this field when editingItem is true. In tandem with the logic of the text span, the input will seamlessly appear when the user double-clicks the text field
  • The input is disabled if itemChecked is true
  • The input will call doneEdit if the user presses enter, or clicks somewhere outside of the input
  • The input will call cancelEdit if the user presses esc

Delete Item Button

The last thing we will need for this template is a button to remove the item from the Checklist

1<!-- Delete Item Button -->2<p class="control">3  <button class="button is-danger" @click="deleteItem">4    <b-icon icon="close" />5  </button>6</p>


To finish the template, we will wrap all those pieces into a <b-field> tag

1<b-field>2  <!-- Item Finished Checkbox -->3  <b-checkbox v-model="itemChecked" />4
5  <!-- Item Description Text -->6  <span7    class="item-static"8    :class="{'item-checked': itemChecked}"9    v-show="!editingItem"10    @dblclick="editItem"11  >12    {{itemTitleDone}}13  </span>14
15  <!-- Edit Item Description Input -->16  <b-input17    v-model="itemTitleEdit"18    v-show="editingItem"19    :disabled="itemChecked"20    @blur="doneEdit"21    @keyup.native.enter="doneEdit"22    @keyup.native.esc="cancelEdit"23    expanded24  />25
26  <!-- Delete Item Button -->27  <p class="control">28    <button class="button is-danger" @click="deleteItem">29      <b-icon icon="close" />30    </button>31  </p>32</b-field>

Writing the Script

Next, we will work on the JavaScript file located at src/components/Checklist/ChecklistItem/script.js.


The name of the component with be ChecklistItem:

1const name = 'ChecklistItem';


We don't have any components to register for this component.


The ChecklistItem component requires two props, which we get from the checklistItems list in the Checklist component.

1const props = {2  indexKey: { type: Number, required: true },3  itemTitle: { type: String, required: true },4};


According to our template, we will need four properties in our data object:

  • Whether or not the current item is checked
  • Whether or not the current item is being edited
  • The description of an item to show in the text span
  • The description of an item to show in the edit item input field
1const data = function () {2  return {3    itemChecked: false,4    editingItem: false,5    itemTitleDone: this.itemTitle,6    itemTitleEdit: this.itemTitle,7  };8};


The methods we will need for this component are operations to edit item, confirm edit, cancel edit, and delete item.


editItem will set the value of editingItem to true if the item hasn’t already been checked.

1const editItem = function () {2  if (!this.itemChecked) {3    this.editingItem = true;4  }5};

cancelItem will revert the item back to its previous description and hides the editing input field.

1const cancelEdit = function () {2  this.editingItem = false;3  this.itemTitleEdit = this.itemTitleDone;4};

doneEdit will confirm the edited changes, and will set the text value of the span to be equal to those changes. If the value that is entered is blank, then the item will be deleted.

1const doneEdit = function () {2  this.itemTitleDone = this.itemTitleEdit;3  this.editingItem = false;4  if (this.itemTitleDone === '') {5    this.deleteItem();6  }7};

deleteItem will delete the item from the parent Checklist component.

1const deleteItem = function () {2  this.$parent.deleteItem(this.indexKey);3};

Exporting the script

With the script logic written, we need to export it in the same way you export in a standard Vue file:

1export default {2  name,3  components: {},4  props,5  data,6  computed: {},7  methods: {8    editItem,9    cancelEdit,10    doneEdit,11    deleteItem,12  },13};

Finishing the Script

1// ==================2// NAME3// ==================4const name = 'ChecklistItem';5
6// ==================7// COMPONENTS8// ==================9const components = {};10
11// ==================12// PROPS13// ==================14const props = {15  indexKey: { type: Number, required: true },16  itemTitle: { type: String, required: true },17};18
19// ================20// DATA21// ================22const data = function () {23  return {24    itemChecked: false,25    editingItem: false,26    itemTitleDone: this.itemTitle,27    itemTitleEdit: this.itemTitle,28  };29};30
31// ================32// COMPUTED33// ================34const computed = {};35
36// =================37// METHODS38// =================39
40/**41 * Sets the value of 'editingItem' to true if the item42 * hasn't already been checked off as completed43 */44const editItem = function () {45  if (!this.itemChecked) {46    this.editingItem = true;47  }48};49
50/**51 * Reverts the item back to its previous description52 * and hides the editing input field53 */54const cancelEdit = function () {55  this.editingItem = false;56  this.itemTitleEdit = this.itemTitleDone;57};58
59/**60 * Sets the description of the item to the value of the61 * input field that is used to edit the description. If the user62 * has entered a blank value, the item is deleted63 */64const doneEdit = function () {65  this.itemTitleDone = this.itemTitleEdit;66  this.editingItem = false;67  if (this.itemTitleDone === '') {68    this.deleteItem();69  }70};71
72/**73 * Deletes the item from the parent Checklist component74 */75const deleteItem = function () {76  this.$parent.deleteItem(this.indexKey);77};78
79export default {80  name,81  components,82  props,83  data,84  computed,85  methods: {86    editItem,87    cancelEdit,88    doneEdit,89    deleteItem,90  },91};

Writing the CSS

Finally, we will add a bit of styling in the src/components/Checklist/ChecklistItem/style.css file.

Like the Checklist component, we will be keeping the styling simple here. We want the text span of the item to expand to fill the empty space within its container, and we want to give it a border to make the transition between editing and non-editing modes more seamless.

We also want to create a rule for the item-checked class, to put a line through the text of the completed item in the Checklist

1.item-static {2  width: 100%;3  width: -moz-available;4  width: -webkit-fill-available;5  width: fill-available;6  display: flex;7  align-items: center;8  border: 1px #dbdbdb solid;9  padding-left: 10px;10}11
12.item-checked {13  text-decoration: line-through;14}

Lets Compare

Alright, our components are in place and

This is what the Checklist.vue file would look like if you followed the format specified in the official Vue documentation.

1<template>2  <div class="container is-fluid">3    <div class="section">4      <div class="checklist-box">5        <!-- Header -->6        <h1>Checklist</h1>7
8        <!-- New Item Input -->9        <b-field>10          <b-input v-model="newItem" expanded @keyup.native.enter="addItem" />11          <p class="control">12            <button class="button is-primary" @click="addItem">Add</button>13          </p>14        </b-field>15
16        <hr v-show="checklistItems.length > 0" />17
18        <!-- Checklist Items -->19        <ChecklistItem20          v-for="item in checklistItems"21          :key="item.key"22          :itemTitle="item.title"23          :indexKey="item.key"24        />25      </div>26    </div>27  </div>28</template>29
30<script>31  import ChecklistItem from '@/components/Checklist/ChecklistItem/ChecklistItem';32  export default {33    name: 'Checklist',34    components: {35      ChecklistItem: ChecklistItem,36    },37    props: {},38    data() {39      return {40        checklistItems: [],41        newItem: '',42      };43    },44    computed: {},45    methods: {46      addItem: function () {47        let key = 0;48        if (this.checklistItems.length !== 0) {49          key = this.checklistItems[this.checklistItems.length - 1].key + 1;50        }51        this.checklistItems.push({ key, title: this.newItem });52        this.newItem = '';53      },54      deleteItem: function (indexKey) {55        for (let i = 0; i < this.checklistItems.length; i++) {56          if (this.checklistItems[i].key === indexKey) {57            this.checklistItems.splice(i, 1);58            break;59          }60        }61      },62    },63  };64</script>65
66<style>67  .checklist-box {68    margin-left: auto;69    margin-right: auto;70    width: 85%;71    border-radius: 5px;72    border: 1px solid #e7eaec;73    box-shadow: 0px 0px 4px rgba(134, 134, 134, 0.21);74    padding: 15px 15px 15px 15px;75  }76</style>

and here is the ChecklistItem.vue file with the same standard format:

1<template>2  <b-field>3    <b-checkbox v-model="itemChecked" />4    <span5      class="item-static"6      :class="{'item-checked': itemChecked}"7      v-show="!editingItem"8      @dblclick="editItem"9    >10      {{itemTitleDone}}11    </span>12    <b-input13      v-model="itemTitleEdit"14      v-show="editingItem"15      :disabled="itemChecked"16      @blur="doneEdit"17      @keyup.native.enter="doneEdit"18      @keyup.native.esc="cancelEdit"19      expanded20    />21    <p class="control">22      <button class="button is-danger" @click="deleteItem">23        <b-icon icon="close" />24      </button>25    </p>26  </b-field>27</template>28
29<script>30  export default {31    name: 'ChecklistItem',32    props: {33      indexKey: { type: Number, required: true },34      itemTitle: { type: String, required: true },35    },36    data() {37      return {38        itemChecked: false,39        editingItem: false,40        itemTitleDone: this.itemTitle,41        itemTitleEdit: this.itemTitle,42      };43    },44    computed: {},45    methods: {46      editItem: function () {47        if (!this.itemChecked) {48          this.editingItem = true;49        }50      },51      cancelEdit: function () {52        this.editingItem = false;53        this.itemTitleEdit = this.itemTitleDone;54      },55      doneEdit: function () {56        this.itemTitleDone = this.itemTitleEdit;57        this.editingItem = false;58        if (this.itemTitleDone === '') {59          this.deleteItem();60        }61      },62      deleteItem: function () {63        this.$parent.deleteItem(this.indexKey);64      },65    },66  };67</script>68
69<style>70  .item-static {71    width: 100%;72    width: -moz-available;73    width: -webkit-fill-available;74    width: fill-available;75    display: flex;76    align-items: center;77    border: 1px #dbdbdb solid;78    padding-left: 10px;79  }80
81  .item-checked {82    text-decoration: line-through;83  }84</style>

While both of these examples are manageable, they are certainly becoming quite long files. These are fairly simple components as well; so trying to build something more involved simply will not scale well. Also notice that none of the functions have any comments or documentation. I find that the structure of the <script/> tag makes the code difficult to read to begin with, as it forces you to compress everything into a small space. Notice how the methods begin with three levels of indentation; this is horizontal space that would be nice to have back, especially for writing comments or longer statements. Separating the JavaScript into its own file allows you to make everything more readable, and gives you more space to work.

Splitting the CSS file out of the .vue file can also be very helpful, especially if you use classes that are repeated in many different component templates.

Wrapping Up

Vue is a great framework to quickly get an app up and running, and has great developer support as well. I think it is a worthy alternative to other frameworks like React and Angular. My initial impression of Vue is that it would be a good choice for a weekend project or small prototype, and that it wouldn’t scale well because of how .vue files are recommended to be formatted. By splitting the .vue files into smaller pieces, it seems to me that Vue is a much more viable option for larger projects. If you have been on the fence about starting a project in Vue, I highly recommend giving it a shot.

How do you structure your Vue projects? Do you use the standard .vue format? How have you tackled issues of scalability, maintainability, and readability. Feel free to reach out and let us know!