Add/remove list items in Vue.js built with Bulma/Buefy

By: (plus.google.com) +David Herron; Date: July 21, 2018

Tags: Vue.js » JavaScript

Most applications with item lists you want to add or remove individual items. With Vue.js it's easy and obvious how to render an item list. What's not so obvious is how to manipulate the list afterwards. The Vue.js documentation doesn't say how to remove items or change items.

Let's start with a basic first step - rendering a list of items.

With a list of items in managed data like:

data() {
    return {
        ...
        items: [
            {
                id: "videos",
                label: "Videos"
            },
            {
                id: "show-books",
                label: "Show Books"
            },
            {
                id: "music",
                label: "Music"
            },
            {
                id: "pictures",
                label: "Pictures"
            }
        ]
    }
}

The items list can be rendered in a template as so:

<ul id="item-list">
    <li v-for="(item, index) of items" v-bind:key="index" :id="item.id">
        {{ item.label }}
    </li>
</ul>

The v-for attribute is like a for loop in that it will render a sequence of the named HTML element. The construction of the HTML element will depend on other attributes, and the child components. It's quite flexible and powerful. See documentation: (vuejs.org) https://vuejs.org/v2/guide/list.html

What we want to focus on is adding/removing items from the list. The Vue.js Guide page says that manipulating the array causes Array Change Detection to cause a re-rendering.

For this tutorial we will create a simple Vue.js application using the Bulma/Buefy UI toolkit, and explore adding and removing items from a list. The use of Bulma/Buefy does not change anything about list add/remove behaviors. We're using the toolkit simply to make the UI a little nicer.

In a companion tutorial we will go over simple form validation: Rudimentary form validation in Vue.js with Buefy/Bulma

An example application

We need the Vue.js CLI tool installed. See Getting started with Vue.js application development

$ vue init webpack-simple list-add-delete

Let's get right into the surgery. If you need a tour of the skeleton see Getting started with Vue.js application development

In index.html there is one line to add:

<link rel="stylesheet" href="//cdn.materialdesignicons.com/2.0.46/css/materialdesignicons.min.css">

This sets up the Material Design icons so they can be easily used in a Buefy/Bulma UI.

In App.vue insert these <template> and <style> tags:

<template>
  <div id="list-add-delete" class="columns">
    <section id="items-area" class="column">
      <ul id="item-list">
        <li v-for="(item, index) of items" v-bind:key="index" :id="item.id">
          {{ item.item }}
          <button class="button is-medium is-primary"
              @click="removeItem(index)"><b-icon icon="close-box-outline"></b-icon></button>
        </li>
      </ul>
    </section>
    <section id="new-item-form" class="column">
        <div class="field">
            <b-switch v-model="deleteWithSplice">
                {{ deleteWithSplice ? ".splice" : "$delete" }}
            </b-switch>
        </div>
        <b-field horizontal label="id">
            <b-input v-model="newId"></b-input>
        </b-field>
        <b-field horizontal label="label">
            <b-input v-model="newItem"></b-input>
        </b-field>
        <button class="button is-medium is-primary"
            @click="addNewItem">Add</button>
    </section>
  </div>
</template>

...

<style scoped>
#list-add-delete {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 12px;
}

#item-list, 
#item-list li  {
  list-style: disc inside;
}

#new-item-form {
  margin: 10px;
}
</style>

We have a simple list rendered from an array in items. Each item has a couple fields, where id is used for the id attribute, and item is used as the body text of the list item. Additionally each list item has a button that will be used for removing that item from the array.

The second section is a simple form with which we will enter new items.

And we've added a little bit of styling. By default it seems Bulma/Buefy makes lists where the disc is not showing, so we've ensured it does show, and we've set up a little bit of other styling.

The list and the form for new lists will show up side-by-side. This is due to using a Bulma columns construct.

For the code to drive this, change the <script> tag in App.vue to this:

<script>
export default {
  name: 'list-add-delete',
  data () {
    return {
      items: [
        { id: "foo", item: "Foo" },
        { id: "goo", item: "Goo" }
      ],
      newId: "",
      newItem: "",
      deleteWithSplice: true,
    }
  },
  methods: {
    addNewItem() {
        if (this.newId === "" || this.newItem === "") return;
        this.items.push({
          id: this.newId,
          item: this.newItem
        });
        this.newId = "";
        this.newItem = "";
    },
    removeItem(index) {
      if (this.deleteWithSplice) {
        this.items.splice(index, 1);
      } else {
        this.$delete(this.items, index);
      }
    },
  }
}
</script>

In the data, the items array is what's used for rendering the list. The newId and newItem values are used while adding new items, as the name implies. The deleteWithSplice value determines whether to delete array values using the splice function or the $delete function of Vue.js.

Vue.js will recognize removing list items by manipulating the array, such as by using this.items.splice as shown here. Vue.js also provides a $delete function, which corresponds to Vue.delete, which is used for deleting a property from an object. See (vuejs.org) https://vuejs.org/v2/api/#Vue-delete

We want to be able to try either.

In this application we've demonstrated adding a list item using push and removing one using either splice or $delete. According to the Vue.js documentation other array manipulations are possible. For example, sorting the array would be interesting. Bottom line is that Vue.js promises that manipulating the array automatically bubbles changes out to the user interface.

Without further ado, here is the resulting application. It shows a couple additional that we haven't discussed in this page.

« Doctor Who: The Three Doctors, William Hartnell, Patrick Troughton, and Jon Pertwee Doctor #13, new faces/worlds/times means no old villians means what? »
2016 Election 2018 Elections Acer C720 Ad block Air Filters Air Quality Air Quality Monitoring AkashaCMS Amazon Amazon Kindle Amazon Web Services America Amiga and Jon Pertwee Android Anti-Fascism AntiVirus Software Apple Apple Hardware History Apple iPhone Apple iPhone Hardware April 1st Arduino ARM Compilation Artificial Intelligence Astronomy Astrophotography Asynchronous Programming Authoritarianism Automated Social Posting AWS DynamoDB AWS Lambda Ayo.JS Bells Law Big Brother Big Data Big Finish Big Science Bitcoin Mining Black Holes Blade Runner Blockchain Blogger Blogging Books Botnets Cassette Tapes Cellphones China China Manufacturing Christopher Eccleston Chrome Chrome Apps Chromebook Chromebox ChromeOS CIA CitiCards Citizen Journalism Civil Liberties Climate Change Clinton Cluster Computing Command Line Tools Comment Systems Computer Accessories Computer Hardware Computer Repair Computers Conservatives Cross Compilation Crouton Cryptocurrency Curiosity Rover Currencies Cyber Security Cybermen Cybersecurity Daleks Darth Vader Data backup Data Formats Data Storage Database Database Backup Databases David Tenant DDoS Botnet Department of Defense Department of Justice Detect Adblocker Developers Editors Digital Nomad Digital Photography Diskless Booting Disqus DIY DIY Repair DNP3 Do it yourself Docker Docker MAMP Docker Swarm Doctor Who Doctor Who Paradox Doctor Who Review Drobo Drupal Drupal Themes DVD E-Books E-Readers Early Computers eGPU Election Hacks Electric Bicycles Electric Vehicles Electron Eliminating Jobs for Human Emdebian Encabulators Energy Efficiency Enterprise Node EPUB ESP8266 Ethical Curation Eurovision Event Driven Asynchronous Express Face Recognition Facebook Fake News Fedora VirtualBox Fifth Doctor File transfer without iTunes FireFly Flash Flickr Fraud Freedom of Speech Front-end Development G Suite Gallifrey Gig Economy git Github GitKraken Gitlab GMAIL Google Google Chrome Google Gnome Google+ Government Spying Great Britain Green Transportation Hate Speech Heat Loss Hibernate High Technology Hoax Science Home Automation HTTP Security HTTPS Human ID I2C Protocol Image Analysis Image Conversion Image Processing ImageMagick In-memory Computing InfluxDB Infrared Thermometers Insulation Internet Internet Advertising Internet Law Internet of Things Internet Policy Internet Privacy iOS iOS Devices iPad iPhone iPhone hacking Iron Man iShowU Audio Capture iTunes Janet Fielding Java JavaFX JavaScript JavaScript Injection JDBC John Simms Journalism Joyent Kaspersky Labs Kext Kindle Kindle Marketplace Large Hadron Collider Lets Encrypt LibreOffice Linux Linux Hints Linux Single Board Computers Logging Mac Mini Mac OS Mac OS X MacBook Pro Machine Learning Machine Readable ID Macintosh macOS macOS High Sierra macOS Kext MacOS X setup Make Money Online Make Money with Gigs March For Our Lives MariaDB Mars Mass Violence Matt Lucas MEADS Anti-Missile Mercurial MERN Stack Michele Gomez Micro Apartments Microsoft Military AI Military Hardware Minification Minimized CSS Minimized HTML Minimized JavaScript Missy Mobile Applications Mobile Computers MODBUS Mondas Monetary System MongoDB Mongoose Monty Python MQTT Music Player Music Streaming MySQL NanoPi Nardole NASA Net Neutrality Network Attached Storage Node Web Development Node.js Node.js Database Node.js Performance Node.js Testing Node.JS Web Development Node.x North Korea npm NVIDIA NY Times Online advertising Online Community Online Fraud Online Journalism Online Photography Online Video Open Media Vault Open Source Open Source and Patents Open Source Governance Open Source Licenses Open Source Software OpenAPI OpenJDK OpenVPN Palmtop PDA Patrick Troughton PayPal Paywalls Personal Flight Peter Capaldi Peter Davison Phishing Photography PHP Plex Plex Media Server Political Protest Politics Postal Service Power Control President Trump Privacy Private E-mail server Production use Public Violence Raspberry Pi Raspberry Pi 3 Raspberry Pi Zero ReactJS Recaptcha Recycling Refurbished Computers Remote Desktop Removable Storage Republicans Retro Computing Retro-Technology Reviews RFID Rich Internet Applications Right to Repair River Song Robotics Robots Rocket Ships RSS News Readers rsync Russia Russia Troll Factory Russian Hacking Rust SCADA Scheme Science Fiction SD Cards Search Engine Ranking Season 1 Season 10 Season 11 Security Security Cameras Server-side JavaScript Serverless Framework Servers Shell Scripts Silence Simsimi Skype SmugMug Social Media Social Media Networks Social Media Warfare Social Network Management Social Networks Software Development Software Patents Space Flight Space Ship Reuse Space Ships SpaceX Spear Phishing Spring Spring Boot Spy Satellites SQLite3 SSD Drives SSD upgrade SSH SSH Key SSL Stand For Truth Strange Parts Swagger Synchronizing Files Tegan Jovanka Telescopes Terrorism The Cybermen The Daleks The Master Time-Series Database Tom Baker Torchwood Total Information Awareness Trump Trump Administration Trump Campaign Twitter Ubuntu Udemy UDOO US Department of Defense Video editing Virtual Private Networks VirtualBox VLC VNC VOIP Vue.js Walmart Weapons Systems Web Applications Web Developer Resources Web Development Web Development Tools Web Marketing Webpack Website Advertising Weeping Angels WhatsApp William Hartnell Window Insulation Windows Windows Alternatives Wordpress World Wide Web Yahoo YouTube YouTube Monetization