Vue CLI 3 Full-Stack App Structure

Vue CLI 3 Full-Stack App Structure

If you're creating an app with Vue.js, you'll most likely want to utilize the best-practice scaffolding provided by Vue CLI 3.

If you're creating an app with Vue.js, you'll most likely want to utilize the best-practice scaffolding provided by Vue CLI 3.

But if the Vue app is the client layer of a full-stack JavaScript app, for example, in a “MEVN” configuration (Mongo, Express, Vue, Node), it’s not entirely clear how Vue CLI 3 should be integrated into such a structure.

There are several approaches you could reasonably take:

  1. Put your server in a completely separate repo
  2. Create a repo for your server and put your Vue CLI 3 scaffold in a sub-folder
  3. Create a “universal” structure by modifying your Vue CLI 3 scaffold to share with your server
  4. Conclude that it is not appropriate to use Vue CLI 3 for a full-stack structure and roll your own config.

The difficulty of choosing one of these options is that each has its own pros and cons when it comes to balancing best practices, maintainability, ease of use, ease of testing and deployment etc.

Making this choice was of particular interest to me as I thought about the best approach to take for my Enterprise Vue course, which is centered around the creation of a MEVN app. I was hoping it would be possible to build this app and still take advantage of Vue CLI 3.

Deferring to authority and experience

As far as I know, there is no “official” example of Vue CLI 3 in a full-stack configuration, and I imagine there is unlikely to ever be.

But we can look at how other JavaScipt frameworks have tackled this issue.

A popular and well-respected full-stack app boilerplate is the one outlined at mean.io for a full-stack Angular app.

This boilerplate, and in fact almost all of the full-stack JavaScript boilerplates I could find, use the universal approach I mentioned, where both the client and server share the same directory, giving you a structure like this:

- client
  - components
    ...
  main.js
- server
  - routes
    ...
  index.js
  ...
package.json
...


Interestingly, the mean.io boilerplate also includes Angular CLI.

Universal folder structure pros and cons

By looking at examples out on in the wild, it seems this approach is the most popular way to structure a full-stack JS app.

Some of the advantages I can see are:

  • It’s efficient, as it allows you to share package.json, node_modules, environment variables and opens the possibility of common code between client and server.
  • It makes installation and deployment easy, as one command in package.json can be used to install/deploy the whole app.
  • It’s easy to read and understand.

The disadvantage is that if you want to use this app structure with Vue CLI 3, you’ll need to modify the scaffold, which is not without its shortcomings.

Accommodating a server in a Vue CLI 3 scaffold

Vue CLI 3 hasn’t been designed to share its space with a server. By going down this path a few of the problems you’ll face include:

  • It’s efficient, as it allows you to share package.json, node_modules, environment variables and opens the possibility of common code between client and server.
  • It makes installation and deployment easy, as one command in package.json can be used to install/deploy the whole app.
  • It’s easy to read and understand.

None of these problems are insurmountable, though, and if you can get through them you’ll have a clean, maintainable folder structure, with the best practices and zero-config advantages of Vue CLI 3.

Node.js, ExpressJs, MongoDB and Vue.js (MEVN Stack) Application Tutorial

Node.js, ExpressJs, MongoDB and Vue.js (MEVN Stack) Application Tutorial

In this tutorial, you'll learn how to integrate Vue.js with Node.js backend (using Express framework) and MongoDB and how to build application with Node.js, ExpressJs, MongoDB and Vue.js

In this tutorial, you'll learn how to integrate Vue.js with Node.js backend (using Express framework) and MongoDB and how to build application with Node.js, ExpressJs, MongoDB and Vue.js

Vue.js is a JavaScript framework with growing number of users. Released 4 years ago, it’s now one of the most populare front-end frameworks. There are some reasons why people like Vue.js. Using Vue.js is very simple if you are already familiar with HTML and JavaScript. They also provide clear documentation and examples, makes it easy for starters to learn the framework. Vue.js can be used for both simple and complex applications. If your application is quite complex, you can use Vuex for state management, which is officially supported. In addition, it’s also very flexible that yu can write template in HTML, JavaScript or JSX.

This tutorial shows you how to integrate Vue.js with Node.js backend (using Express framework) and MongoDB. As for example, we’re going to create a simple application for managing posts which includes list posts, create post, update post and delete post (basic CRUD functionality). I divide this tutorial into two parts. The first part is setting up the Node.js back-end and database. The other part is writing Vue.js code including how to build .vue code using Webpack.

Dependencies

There are some dependencies required for this project. Add the dependencies below to your package.json. Then run npm install to install these dependencies.

  "dependencies": {
    "body-parser": "~1.17.2",
    "dotenv": "~4.0.0",
    "express": "~4.16.3",
    "lodash": "~4.17.10",
    "mongoose": "~5.2.9",
    "morgan": "~1.9.0"
  },
  "devDependencies": {
    "axios": "~0.18.0",
    "babel-core": "~6.26.3",
    "babel-loader": "~7.1.5",
    "babel-preset-env": "~1.7.0",
    "babel-preset-stage-3": "~6.24.1",
    "bootstrap-vue": "~2.0.0-rc.11",
    "cross-env": "~5.2.0",
    "css-loader": "~1.0.0",
    "vue": "~2.5.17",
    "vue-loader": "~15.3.0",
    "vue-router": "~3.0.1",
    "vue-style-loader": "~4.1.2",
    "vue-template-compiler": "~2.5.17",
    "webpack": "~4.16.5",
    "webpack-cli": "^3.1.0"
  },

Project Structure

Below is the overview of directory structure for this project.

  app
    config
    controllers
    models
    queries
    routes
    views
  public
    dist
    src

The app directory contains all files related to server-side. The public directory contains two sub-directories: dist and src. dist is used for the output of build result, while src is for front-end code files.

Model

First, we define a model for Post using Mongoose. To make it simple, it only has two properties: title and content.

app/models/Post.js

  const mongoose = require('mongoose');

  const { Schema } = mongoose;

  const PostSchema = new Schema(
    {
      title: { type: String, trim: true, index: true, default: '' },
      content: { type: String },
    },
    {
      collection: 'posts',
      timestamps: true,
    },
  );

  module.exports = mongoose.model('Post', PostSchema);

Queries

After defining the model, we write some queries that will be needed in the controllers.

app/queries/posts.js

  const Post = require('../models/Post');

  /**
   * Save a post.
   *
   * @param {Object} post - Javascript object or Mongoose object
   * @returns {Promise.}
   */
  exports.save = (post) => {
    if (!(post instanceof Post)) {
      post = new Post(post);
    }

    return post.save();
  };

  /**
   * Get post list.
   * @param {object} [criteria] - Filter options
   * @returns {Promise.<Array.>}
   */
  exports.getPostList = (criteria = {}) => Post.find(criteria);

  /**
   * Get post by ID.
   * @param {string} id - Post ID
   * @returns {Promise.}
   */
  exports.getPostById = id => Post.findOne({ _id: id });

  /**
   * Delete a post.
   * @param {string} id - Post ID
   * @returns {Promise}
   */
  exports.deletePost = id => Post.findByIdAndRemove(id);

Controllers

We need API controllers for handling create post, get post listing, get detail of a post, update a post and delete a post.

app/controllers/api/posts/create.js

  const postQueries = require('../../../queries/posts');

  module.exports = (req, res) => postQueries.save(req.body)
    .then((post) => {
      if (!post) {
        return Promise.reject(new Error('Post not created'));
      }

      return res.status(200).send(post);
    })
    .catch((err) => {
      console.error(err);

      return res.status(500).send('Unable to create post');
    });

app/controllers/api/posts/delete.js

  const postQueries = require('../../../queries/posts');

  module.exports = (req, res) => postQueries.deletePost(req.params.id)
    .then(() => res.status(200).send())
    .catch((err) => {
      console.error(err);

      return res.status(500).send('Unable to delete post');
    });

app/controllers/api/posts/details.js

  const postQueries = require('../../../queries/posts');

  module.exports = (req, res) => postQueries.getPostById(req.params.id)
    .then((post) => {
      if (!post) {
        return Promise.reject(new Error('Post not found'));
      }

      return res.status(200).send(post);
    })
    .catch((err) => {
      console.error(err);

      return res.status(500).send('Unable to get post');
    });

app/controllers/api/posts/list.js

  const postQueries = require('../../../queries/posts');

  module.exports = (req, res) => postQueries.getPostList(req.params.id)
    .then(posts => res.status(200).send(posts))
    .catch((err) => {
      console.error(err);

      return res.status(500).send('Unable to get post list');
    });

app/controllers/api/posts/update.js

  const _ = require('lodash');

  const postQueries = require('../../../queries/posts');

  module.exports = (req, res) => postQueries.getPostById(req.params.id)
    .then(async (post) => {
      if (!post) {
        return Promise.reject(new Error('Post not found'));
      }

      const { title, content } = req.body;

      _.assign(post, {
        title, content
      });

      await postQueries.save(post);

      return res.status(200).send({
        success: true,
        data: post,
      })
    })
    .catch((err) => {
      console.error(err);

      return res.status(500).send('Unable to update post');
    });

Routes

We need to have some pages for user interaction and some API endpoints for processing HTTP requests. To make the app scalable, it’s better to separate the routes for pages and APIs.

app/routes/index.js

  const express = require('express');

  const routes = express.Router();

  routes.use('/api', require('./api'));
  routes.use('/', require('./pages'));

  module.exports = routes;


Below is the API routes.

app/routes/api/index.js

  const express = require('express');

  const router = express.Router();

  router.get('/posts/', require('../../controllers/api/posts/list'));
  router.get('/posts/:id', require('../../controllers/api/posts/details'));
  router.post('/posts/', require('../../controllers/api/posts/create'));
  router.patch('/posts/:id', require('../../controllers/api/posts/update'));
  router.delete('/posts/:id', require('../../controllers/api/posts/delete'));

  module.exports = router;


For the pages, in this tutorial, we use plain HTML file. You can easily replace it with any HTML template engine if you want. The HTML file contains a div whose id is app. Later, in Vue.js application, it will use the element with id app for rendering the content. What will be rendered on each pages is configured on Vue.js route on part 2 of this tutorial.

app/routes/pages/index.js

  const express = require('express');

  const router = express.Router();

  router.get('/posts/', (req, res) => {
    res.sendFile(`${__basedir}/views/index.html`);
  });

  router.get('/posts/create', (req, res) => {
    res.sendFile(`${__basedir}/views/index.html`);
  });

  router.get('/posts/:id', (req, res) => {
    res.sendFile(`${__basedir}/views/index.html`);
  });

  module.exports = router;

Below is the HTML file

app/views/index.html

  <!DOCTYPE html>
  <html>
    <head>
      <meta charset="utf-8">
      <title>VueJS Tutorial by Woolha.com</title>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" type="text/css" media="all" />
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
      <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    </head>
    <body>
      <div id="app"></div>
      <script src="/dist/js/main.js"></script>
    </body>
  </html>

Below is the main script of the application, you need to run this for starting the server-side application.

app/index.js

  require('dotenv').config();

  const bodyParser = require('body-parser');
  const express = require('express');
  const http = require('http');
  const mongoose = require('mongoose');
  const morgan = require('morgan');
  const path = require('path');

  const dbConfig = require('./config/database');
  const routes = require('./routes');

  const app = express();
  const port = process.env.PORT || 4000;

  global.__basedir = __dirname;

  mongoose.Promise = global.Promise;

  mongoose.connect(dbConfig.url, dbConfig.options, (err) => {
    if (err) {
      console.error(err.stack || err);
    }
  });

  /* General setup */
  app.use(morgan('dev'));
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({ extended: true }));
  app.use(morgan('dev'));

  app.use('/', routes);

  const MAX_AGE = 86400000;

  // Select which directories or files under public can be served to users
  app.use('/', express.static(path.join(__dirname, '../public'), { maxAge: MAX_AGE }));

  // Error handler
  app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
    res.status(err.status || 500);

    if (err.status === 404) {
      res.locals.page = {
        title: 'Not Found',
        noIndex: true,
      };

      console.error(`Not found: ${req.url}`);

      return res.status(404).send();
    }

    console.error(err.stack || err);

    return res.status(500).send();
  });

  http
    .createServer(app)
    .listen(port, () => {
      console.info(`HTTP server started on port ${port}`);
    })
    .on('error', (err) => {
      console.error(err.stack || err);
    });

  process.on('uncaughtException', (err) => {
    if (err.name === 'MongoError') {
      mongoose.connection.emit('error', err);
    } else {
      console.error(err.stack || err);
    }
  });

  module.exports = app;

That’s all for the server side preparation. On the next part, we’re going to set up the Vue.js client-side application and build the code into a single JavaScript file ready to be loaded from HTML.

Then, we build the code using Webpack, so that it can be loaded from HTML. In this tutorial, we’re building a simple application with basic CRUD functionality for managing posts.

Create Vue.js Components

For managing posts, there are three components we’re going to create. The first one is for creating a new post. The second is for editing a post. The other is for managing posts (displaying list of posts and allow post deletion)

First, this is the component for creating a new post. It has one method createPost which validate data and send HTTP request to the server. We use axios for sending HTTP request.

public/src/components/Posts/Create.vue

  <template>
    <b-container>
      <h1 class="d-flex justify-content-center">Create a Post</h1>
      <p v-if="errors.length">
        <b>Please correct the following error(s):</b>
        <ul>
          <li v-for="error in errors">{{ error }}</li>
        </ul>
      </p>
      <b-form @submit.prevent>
        <b-form-group>
          <b-form-input type="text" class="form-control" placeholder="Title of the post" v-model="post.title"></b-form-input>
        </b-form-group>
        <b-form-group>
          <b-form-textarea class="form-control" placeholder="Write the content here" v-model="post.content"></b-form-textarea>
        </b-form-group>
        <b-button variant="primary" v-on:click="createPost">Create Post</b-button>
      </b-form>
    </b-container>
  </template>

  <script>
    import axios from 'axios';

    export default {
      data: () => ({
        errors: [],
        post: {
          title: '',
          content: '',
        },
      }),
      methods: {
        createPost(event) {
          if (event) {
            event.preventDefault();
          }

          if (!this.post.title) {
            this.errors = [];

            if (!this.post.title) {
              this.errors.push('Title required.');
            }

            return;
          }

          const url = 'http://localhost:4000/api/posts';
          const param = this.post;

          axios
            .post(url, param)
            .then((response) => {
              console.log(response);
              window.location.href = 'http://localhost:4000/posts';
            }).catch((error) => {
              console.log(error);
            });
        },
      }
    }
  </script>


Below is the component for editing a post. Of course, we need the current data of the post before editing it. Therefore, there’s fetchPost method called when the component is created. There’s also updatePost method which validate data and call the API for updating post.

public/src/components/Posts/Edit.vue

  <template>
    <b-container>
      <h1 class="d-flex justify-content-center">Edit a Post</h1>
      <p v-if="errors.length">
        <b>Please correct the following error(s):</b>
        <ul>
          <li v-for="error in errors">{{ error }}</li>
        </ul>
      </p>
      <b-form @submit.prevent>
        <b-form-group>
          <b-form-input type="text" class="form-control" placeholder="Title of the post" v-model="post.title"></b-form-input>
        </b-form-group>
        <b-form-group>
          <b-form-textarea class="form-control" placeholder="Write the content here" v-model="post.content"></b-form-textarea>
        </b-form-group>
        <b-button variant="primary" v-on:click="updatePost">Update Post</b-button>
      </b-form>
    </b-container>
  </template>

  <script>
    import axios from 'axios';

    export default {
      data: () => ({
        errors: [],
        post: {
          _id: '',
          title: '',
          content: '',
        },
      }),
      created: function() {
        this.fetchPost();
      },
      methods: {
        fetchPost() {
          const postId = this.$route.params.id;
          const url = `http://localhost:4000/api/posts/${postId}`;

          axios
            .get(url)
            .then((response) => {
              this.post = response.data;
              console.log('this.post;');
              console.log(this.post);
          });
        },
        updatePost(event) {
          if (event) {
            event.preventDefault();
          }

          if (!this.post.title) {
            this.errors = [];

            if (!this.post.title) {
              this.errors.push('Title required.');
            }

            return;
          }

          const url = `http://localhost:4000/api/posts/${this.post._id}`;
          const param = this.post;

          axios
            .patch(url, param)
            .then((response) => {
                console.log(response);
              window.alert('Post successfully saved');
            }).catch((error) => {
              console.log(error);
            });
        },
      }
    }
  </script>


For managing posts, we need to fetch the list of post first. Similar to the edit component, in this component, we have fetchPosts method called when the component is created. For deleting a post, there’s also a method deletePost. If post successfully deleted, the fetchPosts method is called again to refresh the post list.

public/src/components/Posts/List.vue

  <template>
    <b-container>
      <h1 class="d-flex justify-content-center">Post List</h1>
      <b-button variant="primary" style="color: #ffffff; margin: 20px;"><a href="/posts/create" style="color: #ffffff;">Create New Post</a></b-button>
      <b-container-fluid v-if="posts.length">
        <table class="table">
          <thead>
            <tr class="d-flex">
              <td class="col-8">Titleqqqqqqqqq</td>
              <td class="col-4">Actions</td>
            </tr>
          </thead>
          <tbody>
            <tr v-for="post in posts" class="d-flex">
              <td class="col-8">{{ post.title }}</td>
              <td class="col-2"><a v-bind:href="'http://localhost:4000/posts/' + post._id"><button type="button" class="btn btn-primary"><i class="fa fa-edit" aria-hidden="true"></i></button></a></td>
              <td class="col-2"><button type="button" class="btn btn-danger" v-on:click="deletePost(post._id)"><i class="fa fa-remove" aria-hidden="true"></i></button></td>
            </tr>
          </tbody>
        </table>
      </b-container-fluid>
    </b-container>
  </template>

  <script>
    import axios from 'axios';

    export default {
      data: () => ({
        posts: [],
      }),
      created: () => {
        this.fetchPosts();
      },
      methods: {
        fetchPosts() {
          const url = 'http://localhost:4000/api/posts/';

          axios
            .get(url)
            .then((response) => {
              console.log(response.data);
              this.posts = response.data;
          });
        },
        deletePost(id) {
          if (event) {
            event.preventDefault();
          }

          const url = `http://localhost:4000/api/posts/${id}`;
          const param = this.post;

          axios
            .delete(url, param)
            .then((response) => {
              console.log(response);
              console.log('Post successfully deleted');

              this.fetchPosts();
            }).catch((error) => {
              console.log(error);
            });
        },
      }
    }
  </script>


All of the components above are wrapped into a root component which roles as the basic template. The root component renders the navbar which is same across all components. The component for each routes will be rendered on router-view.

public/src/App.vue

  <template>
    <div>
      <b-navbar toggleable="md" type="dark" variant="dark">
        <b-navbar-toggle target="nav_collapse"></b-navbar-toggle>
        <b-navbar-brand to="/">My Vue App</b-navbar-brand>
        <b-collapse is-nav id="nav_collapse">
          <b-navbar-nav>
            <b-nav-item to="/">Home</b-nav-item>
            <b-nav-item to="/posts">Manage Posts</b-nav-item>
          </b-navbar-nav>
        </b-collapse>
      </b-navbar>
      <!-- routes will be rendered here -->
      <router-view />
    </div>
  </template>

  <script>

  export default {
    name: 'app',
    data () {},
    methods: {}
  }
  </script>


For determining which component should be rendered, we use Vue.js’ router. For each routes, we need to define the path, component name and the component itself. A component will be rendered if the current URL matches the path.

public/src/router/index.js

  import Vue from 'vue'
  import Router from 'vue-router'

  import CreatePost from '../components/Posts/Create.vue';
  import EditPost from '../components/Posts/Edit.vue';
  import ListPost from '../components/Posts/List.vue';

  Vue.use(Router);

  let router = new Router({
    mode: 'history',
    routes: [
      {
        path: '/posts',
        name: 'ListPost',
        component: ListPost,
      },
      {
        path: '/posts/create',
        name: 'CreatePost',
        component: CreatePost,
      },
      {
        path: '/posts/:id',
        name: 'EditPost',
        component: EditPost,
      },
    ]
  });

  export default router;


Lastly, we need a main script as the entry point which imports the main App component and the router. Inside, it creates a new Vue instance

webpack.config.js

  import BootstrapVue from 'bootstrap-vue';
  import Vue from 'vue';

  import App from './App.vue';
  import router from './router';

  Vue.use(BootstrapVue);
  Vue.config.productionTip = false;
  new Vue({
    el: '#app',
    router,
    render: h => h(App),
  });

Configure Webpack

For building the code into a single JavaSript file. Below is the basic configuration for Webpack 4.

webpack.config.js

  const { VueLoaderPlugin } = require('vue-loader');

  module.exports = {
    entry: './public/src/main.js',
    output: {
      path: `${__dirname}/public/dist/js/`,
      filename: '[name].js',
    },
    resolve: {
      modules: [
        'node_modules',
      ],
      alias: {
        // vue: './vue.js'
      }
    },
    module: {
      rules: [
        {
          test: /\.css$/,
          use: [
            'vue-style-loader',
            'css-loader'
          ]
        },
        {
          test: /\.vue$/,
          loader: 'vue-loader',
          options: {
            loaders: {
            }
            // other vue-loader options go here
          }
        },
        {
          test: /\.js$/,
          loader: 'babel-loader',
          exclude: /node_modules/
        },
      ]
    },
    plugins: [
      new VueLoaderPlugin(),
    ]

After that, run ./node_modules/webpack/bin/webpack.js. You can add the command to the scripts section of package.json, so you can run Webpack with a shorter command npm run build, as examplified below.

  "dependencies": {
    ...
  },
  "devDependencies": {
    ...
  },
  "scripts": {
    "build": "./node_modules/webpack/bin/webpack.js",
    "start": "node app/index.js"
  },

Finally, you can start to try the application. This code is also available on Woolha.com’s Github.

How to implement server-side pagination in Vue.js with Node.js

How to implement server-side pagination in Vue.js with Node.js

This is a simple example of how to implement server-side pagination in Vue.js with a Node.js backend API.

Originally published at https://jasonwatmore.com
This is a simple example of how to implement pagination in Vue.js with a Node.js backend API.

The example contains a hard coded array of 150 objects split into 30 pages (5 items per page) to demonstrate how the pagination logic works. Styling of the example is done with Bootstap 4.

The tutorial code is available on GitHub at https://github.com/cornflourblue/vue-node-server-side-pagination.

Here it is in action (may take a few seconds for the container to startup):

(See on CodeSandbox at https://codesandbox.io/s/vuejs-node-server-side-pagination-example-0l40x)

Running the Vue.js + Node Pagination Example Locally
  1. Install NodeJS and NPM from https://nodejs.org.
  2. Download or clone the tutorial project source code from https://github.com/cornflourblue/vue-node-server-side-pagination.
  3. Install required npm packages of the backend Node API by running the npm install command in the /server folder.
  4. Start the backend Node API by running npm start in the /server folder,
  5. this will start the API on the URL http://localhost:4000.
  6. Install required npm packages of the frontend Vue.js app by running the npm install command in the /client folder.
  7. Start the Vue.js frontend app by running npm start in the /client folder,
  8. this will build the app with webpack and automatically launch it in a
  9. browser on the URL http://localhost:8080.
Server-Side (Node.js) Pagination Logic

Pagination is handled by the backend Node API with the help of the jw-paginate npm package, for more info on how the pagination logic works see JavaScript - Pure Pagination Logic in Vanilla JS / TypeScript.

Below is the code for the paged items route (/api/items) in the node server file (/server/server.js) in the example, it creates a hardcoded list of 150 items to be paged, in a real application you would replace this with real data (e.g. from a database). The route accepts an optional page parameter in the url query string, if the parameter isn't set it defaults to the first page.

The paginate() function is from the jw-paginate package and accepts the following parameters:

  • totalItems (required) - the total number of items to be paged
  • currentPage (optional) - the current active page, defaults to the first page
  • pageSize (optional) - the number of items per page, defaults to 10
  • maxPages (optional) - the maximum number of page navigation links to display, defaults to 10

The output of the paginate function is a pager object containing all the information needed to get the current pageOfItems out of the items array, and to display the pagination controls in the Vue.js frontend, including:

  • startIndex - the index of the first item of the current page (e.g. 0)
  • endIndex - the index of the last item of the current page (e.g. 9)
  • pages - the array of page numbers to display (e.g. [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ])
  • currentPage - the current active page (e.g. 1)
  • totalPages - the total number of pages (e.g. 30)

I've set the pageSize to 5 in the CodeSandbox example above so the pagination links aren't hidden below the terminal console when the container starts up. In the code on GitHub I didn't set the page size so the default 10 items are displayed per page in that version.

The current pageOfItems is extracted from the items array using the startIndex and endIndex from the pager object. The route then returns the pager object and current page of items in a JSON response.

// paged items route
app.get('/api/items', (req, res, next) => {
   // example array of 150 items to be paged
   const items = [...Array(150).keys()].map(i => ({ id: (i + 1), name: 'Item ' + (i + 1) }));

   // get page from query params or default to first page
   const page = parseInt(req.query.page) || 1;

   // get pager object for specified page
   const pageSize = 5;
   const pager = paginate(items.length, page, pageSize);

   // get page of items from items array
   const pageOfItems = items.slice(pager.startIndex, pager.endIndex + 1);

   // return pager object and current page of items
   return res.json({ pager, pageOfItems });
});

Client-Side (Vue.js) Pagination Component

Since the pagination logic is handled on the server, the only thing the Vue.js client needs to do is fetch the pager information and current page of items from the backend, and display them to the user.

Vue.js Home Page Component

Below is the Vue home page component (/client/src/home/HomePage.vue) from the example. The template renders the current page of items as a list of divs with the v-for directive, and renders the pagination controls using the data from the pager object. Each pagination link sets the page query parameter in the url with the <router-link> component and :to="{ query: { page: ... }}" property.

The Vue component contains a watcher function on the page url query parameter '$route.query.page', the handler function is triggered by Vue whenever the page variable in the url querystring changes, the immediate: true flag tells Vue to also run the function when the component first loads. The watcher function checks if the page has changed and fetches the pager object and pageOfItems for the current page from the backend API with an HTTP request.

The CSS classes used are all part of Bootstrap 4.3, for more info see https://getbootstrap.com/docs/4.3/getting-started/introduction/.

<template>
   <div class="card text-center m-3">
       <h3 class="card-header">Vue.js + Node - Server Side Pagination Example</h3>
       <div class="card-body">
           <div v-for="item in pageOfItems" :key="item.id">{{item.name}}</div>
       </div>
       <div class="card-footer pb-0 pt-3">
           <ul v-if="pager.pages && pager.pages.length" class="pagination">
               <li :class="{'disabled':pager.currentPage === 1}" class="page-item first-item">
                   <router-link :to="{ query: { page: 1 }}" class="page-link">First</router-link>
               </li>
               <li :class="{'disabled':pager.currentPage === 1}" class="page-item previous-item">
                   <router-link :to="{ query: { page: pager.currentPage - 1 }}" class="page-link">Previous</router-link>
               </li>
               <li v-for="page in pager.pages" :key="page" :class="{'active':pager.currentPage === page}" class="page-item number-item">
                   <router-link :to="{ query: { page: page }}" class="page-link">{{page}}</router-link>
               </li>
               <li :class="{'disabled':pager.currentPage === pager.totalPages}" class="page-item next-item">
                   <router-link :to="{ query: { page: pager.currentPage + 1 }}" class="page-link">Next</router-link>
               </li>
               <li :class="{'disabled':pager.currentPage === pager.totalPages}" class="page-item last-item">
                   <router-link :to="{ query: { page: pager.totalPages }}" class="page-link">Last</router-link>
               </li>
           </ul>
       </div>
   </div>
</template>

<script>
export default {
   data () {
       return {
           pager: {},
           pageOfItems: []
       }
   },
   watch: {
       '$route.query.page': {
           immediate: true,
           handler(page) {
               page = parseInt(page) || 1;
               if (page !== this.pager.currentPage) {
                   fetch(`/api/items?page=${page}`, { method: 'GET' })
                       .then(response => response.json())
                       .then(({pager, pageOfItems}) => {
                           this.pager = pager;
                           this.pageOfItems = pageOfItems;
                       });
               }
           }
       }
   }
}
</script>

How to Creat a Task Management App Using Vue.js and a Node.js

How to Creat a Task Management App Using Vue.js and a Node.js

In this article, we will build a simple Task Manager application. We will build it using Node.js in the backend and Vue.js in the frontend. We will have a list of boards, each containing several lists. Each list will contain several cards which will represent the tasks.

Node.js is a Javascript backend framework and has been around for many years. In comparison to more established frameworks for Java, PHP, and Ruby, it is still young. Even with this, there is still some positive news. There are many JavaScript backend frameworks in the top starred projects on GitHub.

Javascript's flexibility allows it to work on both the frontend and backend. There are several components and patterns which seem to be common among many applications: drag-and-drop widgets, rearranging items to change their order, seeding data in the backend for development purposes, editable-inline-fields, a central event system for sending messages across different parts of an application, among others. There are several frontend libraries to help with the above. We will not be using any of them. We will build the above-mentioned features from scratch. This is so that we are aware of how the underlying mechanics of the base web technologies work.

In this article, we will build a simple Task Manager application. We will build it using Node.js in the backend and Vue.js in the frontend. We will have a list of boards, each containing several lists. Each list will contain several cards which will represent the tasks.

Being acquainted with the basic structure of the application, let's start building it. We will need Node.js installed to follow along.

The finished code for this tutorial is accessible at these GitHub repositories:

Initialise the Backend and Frontend Application Folders

In an empty folder, initialize the frontend using

vue init webpack client 

Accept with yes for all the prompts, except for “tests”. Enter the required information where necessary. Also, accept to install the dependencies using npm.

Navigate to the frontend folder using cd client. Install the required packages using;

npm install --save axios

This is for making HTTP calls to the server.

Install the following packages which we will use for compiling Sass:

npm install sass-loader node-sass --save-dev

Navigate to the base folder using cd ../ and create the server folder called server. Navigate to the folder using cd server and create a file named index.js. This will be the entry point for the server. Initialize a new package.json file using npm init. Answer yes to all the prompts or fill in the details if you deem it necessary.

Install the following server packages;

npm install --save body-parser express faker mongoose

The packages we installed are responsible for:

  • body-parser: this helps us to parse and use frontend parameters in the backend.
  • express: A backend framework for Node.js.
  • faker: A library to help create dummy data for seeding database during development.
  • Mongoose: A database ORM library to do operations with the MongoDB database.

In the file index.js, paste in the following:

const mongoose = require('mongoose')
const express = require('express')
const app = express()
const port = 3000
const bodyParser = require('body-parser')
const config = require('./config/index')
const seederService = require('./services/seeder.service');

mongoose.connect(config.dbConnection, { useNewUrlParser: true})

app.use(bodyParser.json())

const corsConfig = function(req, res, next) {
    res.header('Access-Control-Allow-Origin', 'http://localhost:8080')
  res.header('Access-Control-Allow-Credentials', true)
  res.header('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS,POST,PUT')
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization')
  next()
}

app.use(corsConfig);

const apiRoutes = require('./routes/api');
app.use('/api', apiRoutes);

if (config.seedData) {
  seederService.seedData()
}

app.listen(port, () => console.log(Example app listening on port ${port}!))

In the above code, we are initializing the Express.js server. We instruct the server to allow frontend connections from certain URLs — in this case: http://localhost:8080. Next, we import the seeder and config file ./services/seeder.service and ./config/index. These do not exist yet but we will get to that soon. We will only initialize the seeding mechanism if the config option seedData is set to true. This should only for use during development but that choice is up to the developer.

Create the config file in config/index.js and paste in the following:

module.exports = {
  seedData: true,
  dbConnection: "mongodb://127.0.0.1:27017/task-management-system",
  numberOfBoards: 15,
  numberOfListsPerBoard: 8,
  numberOfCardsPerList: 4
}

We will need MongoDB running to carry on with this tutorial. For more information on that, please follow the instructions in the article How to Create a Public File Sharing Service with Vue.js and Node.js. This was published recently.

Create Backend Data Structure For Cards, Lists and Boards

Cards Data Structure

Now, let us create the models for the entities of our application. Still in the server folder; create the board model in the file models/board.model.js and paste in the following:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const Types = Schema.Types;
const List = require("./list.model")

const BoardSchema = new Schema({
  title: Types.String,
  lists: [
    {type: Types.ObjectId, ref: "List", default: []}
  ]
})

module.exports = mongoose.model("Board", BoardSchema, "boards")

Create the list model in the file models/list.model.js and paste in the following:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const Types = Schema.Types;
const Card = require("./card.model")

const ListSchema = new Schema({
  title: Types.String,
  cards: [
    {type: Types.ObjectId, ref: "Card", default: []}
  ]
})

module.exports = mongoose.model("List", ListSchema, "lists")

Create the card model in the file models/card.model.js and paste in the following:

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const Types = Schema.Types;

const CardSchema = new Schema({
  title: Types.String,
  body: Types.String,
})

module.exports = mongoose.model("Card", CardSchema, "cards")

Seed Some Data into the Boards, Cards and Lists Database (MongoDB)

Let us now create the seeder service. This will create some initial data in the database for us to use during development. Create a file in services/seeder.service.js and paste in the following:

const faker = require('faker')
const Board = require('../models/board.model')
const List = require('../models/list.model')
const Card = require('../models/card.model')
const config = require('../config/index')

module.exports = {
  seedData () {
    Board.countDocuments((err, count) => {
      if (count > 0) {
        return;
      }

      this.createBoards()
    })
  },
  createBoards () {
    let boards = [];

    Array.from(Array(config.numberOfBoards)).forEach(() => {
      boards.push({
        title: faker.lorem.sentence(7)
      })
    })

    Board.insertMany(boards, (err, savedBoards) => {
      this.createListsForBoards(savedBoards)
    })
  },
  createListsForBoards (boards) {
    boards.forEach((board) => {
      this.createLists(board)
    })
  },
  createLists (board) {
    let lists = [];
    Array.from(Array(config.numberOfListsPerBoard)).forEach((val, index) => {
      lists.push({
        title: index + faker.lorem.sentence(3),
      })
    })

    List.insertMany(lists, (err, savedLists) => {
      savedLists.forEach((savedList) => {   
        board.lists.push(savedList.id)
      })
      board.save(() => {
        this.createCardsForLists(savedLists)
      })
    })
  },
  createCardsForLists (lists) {
    lists.forEach((list) => {
      this.createCards(list)
    })
  },
  createCards (list) {
    let cards = [];

    Array.from(Array(config.numberOfCardsPerList)).forEach(() => {
      cards.push({
        title: faker.lorem.sentence(5),
        body: faker.lorem.paragraph(1),
      })
    })

    Card.insertMany(cards, (err, savedCards) => {
      savedCards.forEach((savedCard) => {
        list.cards.push(savedCard.id)
      })
      list.save()
    })
  }
}

The method seedData initializes the seeder; we are creating several boards using createBoards. We will create several lists for each of these boards using createListsForBoards. Then, we are creating several cards for each of the lists using createCardsForLists.

Display the Boards, Cards and Lists

Backend

Now that we have the basic infrastructure in place, let's build the routes. These will be responsible for communicating with the frontend.

Create a route file in routes/api.js. Paste in the following:

const express = require("express")
const router = express.Router()
const boardService = require("../services/board.service")

router.get("/boards", boardService.getAll.bind(boardService))
router.get("/boards/:boardId", boardService.getById.bind(boardService))

module.exports = router

This declares the routes to list all the boards. We also have a route to get a single board along with all the nested lists and cards.

Next, create the board-service in services/board.service.js and paste in the following:

const Board = require('../models/board.model')

module.exports = {
  getAll (req, res) {
    Board.find({}, 'title', (err, boards) => {
      this._handleResponse(err, boards, res)
    })
  },
  getById (req, res) {
    Board.findOne({_id: req.params.boardId})
      .populate({
        path: "lists",
        select: ["title"],
        model: "List",
        populate: {
          path: "cards",
          select: ["title", "body"],
          model: "Card"
        }
      })
      .exec((err, board) => {
        this._handleResponse(err, board, res)
      })
  },
  _handleResponse (err, data, res) {
    if (err) {
      res.status(400).end()
    } else {
      res.send(data)
    }
  }
}

This service will handle the requests for the routes above.

Frontend

Now, let's create the frontend files for listing the boards, lists and cards. Navigate to the frontend folder client. In the file src/App.vue, remove the piece of code-line:

<img src="./assets/logo.png">

In the style section, replace it with the following:

<style>
html {
 box-sizing: border-box;
 font-size: 62.5%;
}
body {
 margin: 0;
}
html, body, #app {
 height: 100%;
}
body {
 background-color: #4fc08d;
 font-size: 1.6rem;
 font-family: Helvetica Neue,Arial,Helvetica,sans-serif;
 line-height: 20px;
}
*, *:before, *:after {
 box-sizing: inherit;
}
</style>

This is doing some minimal resets and base styles.

In the file src/main.js, after the line Vue.config.productionTip = false, add the following:

axios.defaults.baseURL = 'http://localhost:3000'

Import the axios library using:

import axios from 'axios'

This configures the axios library to direct all HTTP calls to the URL http://localhost:3000.

To list the boards, open the route file src/router/index.js. Change the existing routes to the following:

import Vue from "vue"
import Router from "vue-router"
import Boards from "@/components/Boards"
import BoardPage from "@/components/BoardPage"

Vue.use(Router)

export default new Router({
 routes: [
  {
   path: "/",
   name: "Boards",
   component: Boards
  },
  {
   path: "/boards/:boardId",
   name: "BoardPage",
   component: BoardPage
  }
 ]
})

We have some pending components to create. Let’s do that now:

First, let’s create the boards component in src/components/Boards.vue. Paste in the following:

<template>
 <div class="boards">
  <router-link v-for="board in boards" class="board" :key="board._id" :to="{ name: 'BoardPage', params: {boardId: board._id }}">
   {{ board.title }}
  </router-link>
 </div>
</template>

<script>
import boardService from "../services/board.service"
export default {
 name: "Boards",
 data () {
  return {
   boards: []
  }
 },
 mounted () {
  boardService.getAll()
   .then(((boards) => {
    this.$set(this, "boards", boards)
   }).bind(this))
 }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.boards {
 width: 80%;
 margin: 0 auto;
 padding-top: 100px;
 display: flex;
 flex-wrap: wrap;
}
.board {
 border-radius: 3px;
 color: #FFFFFF;
 display: block;
 text-decoration: none;
 width: 15%;
 min-width: 150px;
 min-height: 80px;
 padding: 10px;
 background-color: rgb(0, 121, 191);
 margin: 0 15px 15px 0;
}
</style>

The code above uses the board service to fetch the boards from the backend and loops over them to display. We have some CSS styles as well.

Next, create the frontend board service in src/services/board.service.js. Paste in the following:

import axios from "axios"

export default {
 getAll() {
  return axios.get("/api/boards").then(res => res.data)
 },
 findById(boardId) {
  return axios.get("/api/boards/" + boardId).then(res => res.data)
 }
}

Now, create the single-board component in src/components/BoardPage.vue. Put in the following:

<template>
 <div class="board-page-main">
  <template v-if="board">
   <div class="board-title">
    <h2>{{ board.title }}</h2>
   </div>
   <div class="board-lists">
    <div class="board-lists-inner">
     <list 
      v-for="(list, i) in lists" 
      :key="list._id" 
      :index="i" 
      :list-prop="list"/>
    </div>
   </div>
  </template>
 </div>
</template>

<script>
import boardService from "../services/board.service";
import List from "./List";
export default {
 components: {

 },
 data() {
  return {
   board: null,
   lists: []
  };
 },
 created() {
   
 },
 mounted() {
  boardService.findById(this.$route.params.boardId).then(
   (board => {
    this.$set(this, "board", board);
    this.$set(this, "lists", board.lists);
   }).bind(this)
  );
 },
 methods: {
   
 },
};
</script>

<style>
.board-title .is-editing {
 background-color: #ffffff;
 color: #000000;
 padding: 8px;
 display: inline-block;
 min-width: 600px;
}
.add-new-list .is-editing {
 background-color: #ffffff;
 color: #000000;
 padding: 8px;
 margin: 0;
}
</style>

<style scoped lang="scss">
.add-new-list {
 display: inline-block;
 width: 270px;
}
.board-title {
 color: #ffffff;
 padding: 10px;
 height: 90px;
}
.board-page-main {
 height: 100%;
 display: flex;
 flex-direction: column;
}
.board-lists {
 flex-grow: 1;
 margin-bottom: 20px;
 position: relative;
}
.board-lists-inner {
 top: 0;
 right: 0;
 bottom: 0;
 left: 0;
 overflow-x: scroll;
 position: absolute;
 white-space: nowrap;
}
</style>

Then, create the single-list component in src/components/List.vue . Add in the following:

<template>
 <div
  class="board-list"
 >
  <div class="list-inner">
   <div 
    v-if="list" 
    class="list-title">
    <h3>
     {{ list.title }}
    </h3>
   </div>
   <div class="list-cards">
    <card
     v-for="(card, i) in cards"
     :card-prop="card"
     :list-prop="list"
     :key="card._id"
     :index="i"
    />
   </div>
  </div>
 </div>
</template>

<script>
import Card from "./Card"
export default {
 components: {
  Card
 },
 props: [
  "listProp",
  "index"
 ],
 data () {
  return {
   list: null,
   cards: []
  }
 },
 mounted () {
  this.$set(this, "list", this.listProp)
  this.$set(this, "cards", this.listProp.cards)
 },
 methods: {
   
 },
}
</script>

<style>
.list-title .is-editing {
 background-color: #ffffff;
 color: #000000;
}
</style>

<style scoped lang="scss">
.list-inner {
 background-color: #dfe3e6;
 padding: 10px;
 white-space: normal;
 border-radius: 3px;
}
.board-list {
 display: inline-block;
 margin-bottom: 10px;
 margin-right: 10px;
 vertical-align: top;
 width: 270px;
 max-height: 100%;
 overflow-y: scroll;
 &.is-dragging-list {
  transform: rotate(1deg)
 }
 &.drag-entered {
  border: 3px solid #237bda;
 }
}
</style>

For the final component, create the card-component in src/components/Card.vue. Add in the following:

<template>
 <div
  v-if="card"
  class="list-card"
 >
  <div class="card-title">{{ card.title }}</div>
  <div class="card-body">{{ card.body }}</div>
 </div>
</template>

<script>
export default {
 props: ["cardProp", "listProp", "index"],
 data() {
  return {
   card: null,
   list: null
  };
 },
 mounted() {
  this.$set(this, "card", this.cardProp);
  this.$set(this, "list", this.listProp);
 },
 methods: {
   
 },
};
</script>

<style scoped lang="scss">
.card-title {
 text-decoration: underline;
}
.list-card {
 background-color: #ffffff;
 border-radius: 3px;
 padding: 10px;
 margin-bottom: 10px;

 &.is-dragging-card {
  transform: rotate(1deg);
 }
 &.drag-entered {
  border: 3px solid #237bda;
 }
}
</style>

Edit Board Title

Backend

Let's now set up the backend for editing a board title. Navigate to the backend folder. In the file services/board.service.js, add the following method:

update (req, res) {
  Board.findByIdAndUpdate(req.params.boardId, {title: req.body.title}, (err, board) => {
    this._handleResponse(err, board, res)
  })
}

Inside the router routes/api.js, add the following:

router.put("/boards/:boardId", boardService.update.bind(boardService))

Frontend

Now, navigate to the frontend folder. In the component file src/components/BoardPage.vue, locate the code snippet below:

<h2>{{ board.title }}</h2>

And replace it with this one:

<editable
 v-slot:default="slotProps"
 :field-value="board.title"
 @editable-submit="editableSubmitted"
 >
 <h2>{{ slotProps.inputText }}</h2>
</editable>

In the above code, we are invoking a component named Editable, but we are yet to create that. Before we do that, let's explain how it will behave. The component will be a general component responsible for editing text. We expect it to emit an event named editable-submit anytime the user modifies the value. We also pass in a property to act as the initial value to display in the component using :field-value="board.title". Since the component will have a slot section, we passed in the HTML to display in there. Then, we will get access to the component's data scope using v-slot:default="slotProps".

Add this method to src/components/BoardPage.vue to handle the emitted event above:

editableSubmitted(inputText) {
 if (inputText === this.board.title) {
  return;
 }
 boardService.update(this.board._id, inputText).then(() => {
  this.board.title = inputText;
 })
},

Import the Editable component using the line:

import Editable from "./Editable";

And add it to the components list as shown below:

components: {
 List,
 Editable
},

Now, let's create the Editable component. Create a file in src/components/Editable.vue. Paste in the following:

<template>
 <div>
  <h2
   v-show="isEditing"
   ref="editableField"
   :class="{'is-editing': isEditing}"
   contenteditable="true"
   @keydown.enter="submit"
   @blur="onBlur"
   @keydown.esc="escape"
  >{{ inputText }}</h2>
  <template v-if="isEditing === false">
   <div @click="onBoardTitleClick()">
    <slot 
     :isEditing="isEditing" 
     :inputText="inputText"/>
   </div>
  </template>
 </div>
</template>

<script>
export default {
 props: ["fieldValue"],
 data() {
  return {
   inputText: "",
   isEditing: false
  };
 },
 mounted() {
  this.$set(this, "inputText", this.fieldValue);
 },
 methods: {
  onBoardTitleClick() {
   this.$set(this, "isEditing", true);
   setTimeout((() => {
    this.$refs.editableField.focus()
   }).bind(this), 200)
  },
  submit(event) {
   this.$set(this, "inputText", event.currentTarget.innerText)
   this.$emit("editable-submit", event.currentTarget.innerText)
   this.$set(this, "isEditing", false);
  },
  escape(event) {
   this.$set(this, "inputText", event.currentTarget.innerText)
   this.$emit("editable-submit", event.currentTarget.innerText);
   this.$set(this, "isEditing", false);
  },
  onBlur (event) {
   this.$set(this, "inputText", event.currentTarget.innerText)
   this.$emit("editable-submit", event.currentTarget.innerText);
   this.$set(this, "isEditing", false);
  }
 }
};
</script>

In this component, we have a slot section which shows when we are not in edit mode. When in edit mode, the content-editable div is displayed. We are listening to several events. When the title gets clicked, we set the component in edit mode. This will display the content editable div. When in this mode, we can change the title. When we press the escape key, an event called editable-submit is emitted with the updated value to the parent. Likewise, we do the same for when the user presses the enter key. When blurred, we disable edit-mode but keep the changed value if any.

The parent component src/components/BoardPage.vue listens for the editable-submit event. We have not defined the handler yet. Let's do that now. Inside the parent, add the method below:

editableSubmitted(inputText) {
 if (inputText === this.board.title) {
  return;
 }
 boardService.update(this.board._id, inputText).then(() => {
  this.board.title = inputText;
 })
},

This calls the board-service to update the board on the backend. If successful, we set the board title with the value emitted from the Editable component.

In the board-service src/services/board.service.js, add the update method below:

update(boardId, title) {
 return axios.put(
   "/api/boards/" + boardId,
   {
    title: title
   }
  ).then(res => res.data)
}
Add a New List

Backend

Now, let's set up the backend infrastructure to be able to add a new list. Navigate to the backend folder. Create a file in services/list.service.js and add the following:

const List = require('../models/list.model')
const Board = require('../models/board.model')

module.exports = {
  create (req, res) {
    Board.findById(req.body.boardId, (err, board) => {
      if (err) {
        return this._handleResponse(err, null, res)
      }

      if (!board) {
        return this._handleResponse("Error", null, res)
      }

      List.create({title: req.body.title}, (err, card) => {
        board.lists.push(card._id)
        board.save(() => {
          this._handleResponse(err, card, res)
        })
      })
    })
  },
  _handleResponse (err, data, res) {
    if (err) {
      res.status(400).end()
    } else {
      res.send(data)
    }
  }
}

Next, in the route file routes/api.js, add the following:

router.post("/lists", listService.create.bind(listService))

And also import the list-service like below:

const listService = require("../services/list.service")

Frontend

Navigate to the frontend folder. In the file src/components/BoardPage.vue, at the end of the tag:

<div class="board-lists-inner">

Add in the following:

<addable
 class="add-new-list"
 @addable-submit="addableSubmit">
 <div>Add list</div>
</addable>

We introduced another general component called Addable. This is will be responsible for adding new items. It will have a slot inside it as well. We expect it to emit an event called addable-submit.

Let's add a method to handle this event. Inside the file src/components/BoardPage.vue, add the method below:

addableSubmit(listTitle) {
 if (!listTitle || listTitle.length === 0) {
  return;
 }
 listService.create(this.board._id, listTitle).then((newList) => {
  this.board.lists.push(newList)
 })
},

Import the Addable component and the list-service with the following:

import listService from "../services/list.service";
import Addable from "./Addable";

Next, add the Addable component to the list of imported components like below:

components: {
 List,
 Editable,
 Addable,
}

Create a list-service inside src/services/list.service.js. Put in the following:

import axios from "axios"

export default {
 create (boardId, listTitle) {
  return axios.post("/api/lists", {
   boardId: boardId,
   title: listTitle
  }).then(res => res.data)
 }
}

Finally, let's create the component itself. Create a file in src/components/Addable.vue. Paste the following in:

<template>
 <div>
  <h2
   v-show="isAdding"
   ref="addableField"
   :class="{'is-editing': isAdding}"
   contenteditable="true"
   @keydown.enter="submit"
   @blur="onBlur"
   @keydown.esc="escape"
  >{{ inputText }}</h2>
  <h2>{{ inputText }}</h2>
  <template v-if="isAdding === false">
   <div @click="onTitleClick()">
    <slot/>
   </div>
  </template>
 </div>
</template>

<script>
export default {
 data () {
  return {
   isAdding: false,
   inputText: ""
  }
 },
 methods: {
  onTitleClick () {
   this.$set(this, "isAdding", true)
   setTimeout((() => {
    this.$refs.addableField.focus()
   }).bind(this), 200)
  },
  onBlur () {
   this.$set(this, "isAdding", false)
  },
  escape () {
   this.emptyInput()
  },
  submit (event) {
   this.$emit("addable-submit", event.currentTarget.innerText)
   this.emptyInput()
  },
  emptyInput () {
   this.$set(this, "inputText", "")
   this.$refs.addableField.innerText = ""
   this.$set(this, "isAdding", false);
  }
 }
}
</script>

In here, when the text value is clicked, we set the component to add mode. We are showing the slot template when not in add mode. When in add mode, we show the editable div. When the user presses enter, we empty the input and emit an event named addable-submit. When escape is pressed, we empty the input and disable add mode but no event is emitted. When the editable div is blurred, we disable add mode.

Rearrange List

Backend

For our last feature, let's set up the backend feature to rearrange lists. Navigate to the backend folder. Inside routes/api.js, add the following route:

router.put(
 "/boards/updateListsOrder",
 boardService.updateListsOrder.bind(boardService)
)

Rearrange the routes so that the following two are in this order. If not you might have conflicting issues:

router.put(
  "/boards/updateListsOrder",
  boardService.updateListsOrder.bind(boardService)
 )
router.put("/boards/:boardId", boardService.update.bind(boardService))

Inside services/board.service.js, add the method below:

updateListsOrder (req, res) {
  Board.findById(req.body.boardId, (err, board) => {
    if (err) {
      res.status(400).end()
      return
    }

    board.lists = req.body.listIds
    board.save((err, savedBoard) => {
      this._handleResponse(err, savedBoard, res)
    })
  })
},

Frontend

Back to the frontend, inside src/components/BoardPage.vue, add the following data property:

fromListIndex: null,

And the following methods:

onListDragStarted(fromListIndex) {
 this.$set(this, "fromListIndex", fromListIndex)
},
onListDragEnd(event) {
 this.$set(this, "fromListIndex", null);
},
onListDropped(toListIndex) {
 if (this.fromListIndex === toListIndex) {
  return;
 }
 this.switchListPositions(this.fromListIndex, toListIndex);
 this.updateListsOrder();
},
updateListsOrder() {
 let listIds = this.lists.map(list => list._id);
 boardService.updateListsOrder(this.board._id, listIds);
},
switchListPositions(fromListIndex, toListIndex) {
 if (this.fromListIndex === null) {
  return;
 }

 this.lists.splice(toListIndex, 0, this.lists.splice(fromListIndex, 1)[0]);
},

The methods starting with the on keyword will respond to events which happen when we drag a list item. To wire those methods, add the following lines to the created function:

this.$eventBus.$on("list-drag-started", this.onListDragStarted);
this.$eventBus.$on("list-dragend", this.onListDragEnd);
this.$eventBus.$on("list-dropped", this.onListDropped);

Update the board service src/services/board.service.js by adding in this method:

updateListsOrder(boardId, listIds) {
 return axios
  .put("/api/boards/updateListsOrder", {
   boardId: boardId,
   listIds: listIds
  })
  .then(res => res.data)
}

You may notice that we are using an instance property named $eventBus. It is responsible for sending messages across our application. It allows for any component at any level to subscribe to any broadcasted messages. Currently, it does not exist, let's wire it up.

Create a file in src/event-bus/index.js. Paste in the following:

import Vue from "vue"

export default new Vue()

Let's make it available to all Vue instances. Inside src/main.js, import it using:

import eventBus from './event-bus/index'

Then wire it up using the statement:

Vue.prototype.$eventBus = eventBus

It should now be available in every component.

Let's now modify the component src/components/List.vue. In there, in the top level template div node, after:

class="board-list"

Add in the following:

:class="{'is-dragging-list': isDraggingList, 'drag-entered': dragEntered}"
draggable="true"
@dragstart="onListDragStart(index, $event)"
@dragend="onListDragEnd"
@drop="onListDrop(index)"
@dragover.prevent
@dragover="onListDragOver"
@dragleave="onListDragLeave"

Then add the following handlers for the events above:

onListDragStart (fromIndex, event) {
 if (!fromIndex) {
  fromIndex = 0
 }
  
 this.$set(this, "isDraggingList", true)
 this.$eventBus.$emit("list-drag-started", fromIndex)
},
onListDragEnd () {
 this.$set(this, "isDraggingList", false)
 this.$eventBus.$emit("list-dragend")
},
onListDragOver (event) {
 this.$set(this, "dragEntered", true)
},
onListDragLeave (index, list) {
 this.$set(this, "dragEntered", false)
},
onListDrop (toIndex) {
 this.$set(this, "dragEntered", false)
 this.$eventBus.$emit("list-dropped", toIndex)
},

Add in the following data properties:

isDraggingList: false,
dragEntered: false

And, inside src/components/Board.vue, add the following data property:

fromListIndex: null,

Let's figure out what we are doing in the methods above. When we drag a list, it gets a class of is-dragging-list. This tilts the original list some degrees to show that it is the source. When a list is being dragged over, it gets a class of drag-entered. This adds a blue border around the list to show that it is currently being dragged over. When we release a list over another one, the original list takes the position of the one being dragged over. The target list gets shifted to the left.

Conclusion

That brings us to the end of this Task Manager Application. This is only a basic skeleton application. It has many of the basic elements for one to expand. We may have not implemented all the features. There is enough foundation in the code to create a more robust version of the application. Some features you could try to add are: delete feature for cards, lists and boards; draggable feature for cards within the same list or from one list to another; and finally to be able to edit the title for lists and cards as well as the card body.

Thanks For Visiting, Keep Visiting. If you like this tutorial please share it with others.