Building web applications with Vue.js

Vue.js is a progressive JavaScript framework for building user interfaces. It is designed to be easily integrated into existing projects and provides a flexible, scalable solution for front-end development. In this tutorial, we will guide you through the steps of building a web application with Vue.js from scratch.

Prerequisites

Before we begin, you need to have the following installed on your machine:

  • Node.js
  • npm (Node Package Manager)

You can download Node.js from the official website: https://nodejs.org/en/download/.

Getting started

To create a new Vue.js project, we will use the Vue CLI (Command Line Interface). Open your terminal/command prompt and run the following command:

npm install -g @vue/cli

Once the installation is completed, create a new project by running the following command:

vue create my-project

my-project is the name of your project and can be changed to your liking. You will be prompted to select the features you want to include in your project. You can choose the default options or customize them based on your needs. The CLI will then generate a new project in a directory named after your project.

Project structure

The structure of a Vue.js project is similar to that of other web applications. Here is an overview of the files and directories generated by the Vue CLI:

my-project/
โ”œโ”€โ”€ node_modules/   # Dependencies
โ”œโ”€โ”€ public/         # Public assets
โ”‚   โ”œโ”€โ”€ index.html  # HTML entry point
โ”œโ”€โ”€ src/            # Application source code
โ”‚   โ”œโ”€โ”€ assets/     # Static assets
โ”‚   โ”œโ”€โ”€ components/ # Vue components
โ”‚   โ”œโ”€โ”€ App.vue     # Main Vue component
โ”‚   โ””โ”€โ”€ main.js     # Main entry point
โ”œโ”€โ”€ .gitignore      # Git ignore file
โ”œโ”€โ”€ package.json    # Package metadata
โ””โ”€โ”€ README.md       # Project readme
  • node_modules contains all the project dependencies installed by npm.
  • public contains the static assets, such as index.html, used as the entry point for the application.
  • src contains the source code for the application, including Vue components, static assets, and the main entry point.
  • .gitignore specifies the files and directories to be ignored by Git.
  • package.json contains the metadata for the application, including project dependencies and scripts.
  • README.md contains project documentation.

Basic Vue.js Component

In Vue.js, a component defines a reusable UI element. A basic component template consists of a <template>, <script>, and <style> block.

Create a new file named HelloWorld.vue in the src/components directory and add the following code:

<template>
  <div class="hello-world">
    {{ message }}
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data() {
    return {
      message: 'Hello, World!'
    };
  }
};
</script>

<style>
.hello-world {
  font-size: 24px;
  font-weight: bold;
  text-align: center;
  margin-top: 50px;
}
</style>

The <template> block defines the HTML structure of the component. In this case, it is a simple <div> element that displays a message.

The <script> block defines the logic of the component. It exports an object with a name property, which is required for naming the component, and a data function, which returns an object with a message property.

The <style> block defines the styles of the component.

To use the HelloWorld component, import it into the src/App.vue file and add it to the <template> block.

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <HelloWorld />
  </div>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue';

export default {
  name: 'App',
  components: {
    HelloWorld
  }
};
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

The <template> block now includes the HelloWorld component. The <script> block imports the HelloWorld component and registers it with the components property of the App component.

Vue Router

Vue Router is the official routing library for Vue.js. It allows you to define routes for your application and navigate between them.

To use Vue Router in your project, run the following command in your terminal:

npm install vue-router

Once the installation is complete, create a new file named router.js in the src directory and add the following code:

import Vue from 'vue';
import VueRouter from 'vue-router';
import Home from './views/Home.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'home',
    component: Home
  }
];

const router = new VueRouter({
  mode: 'history',
  routes
});

export default router;

The router.js file imports Vue, Vue Router, and the Home component. It then registers Vue Router with Vue using Vue.use(), defines the application routes, and creates a new VueRouter instance.

The mode property specifies the routing mode, which can be either hash or history. In hash mode, the URL is appended with a hash (#) symbol, while in history mode, it uses the HTML5 History API to manipulate the browser history.

To use the router in your application, import it into the src/main.js file and add it to the Vue instance.

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

Vue.config.productionTip = false;

new Vue({
  router,
  render: h => h(App)
}).$mount('#app');

The Vue instance now includes the router property, which is set to the router instance created in router.js.

Vuex

Vuex is a state management pattern and library for Vue.js. It allows you to manage application states in a centralized store, making it easier to manage and debug your application.

To use Vuex in your project, run the following command in your terminal:

npm install vuex

Once the installation is complete, create a new file named store.js in the src directory and add the following code:

import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    increment(state) {
      state.count++;
    },
    decrement(state) {
      state.count--;
    }
  },
  actions: {
    increment(context) {
      context.commit('increment');
    },
    decrement(context) {
      context.commit('decrement');
    }
  },
  getters: {
    getCount(state) {
      return state.count;
    }
  }
});

The store.js file imports Vue and Vuex, registers Vuex with Vue using Vue.use(), and exports a new Vuex store instance.

The store instance contains four properties:

  • state: the application state, which is a plain JavaScript object.
  • mutations: the methods for changing the state. They take the state as the first argument and can be accessed using context.commit().
  • actions: the methods for asynchronous state manipulation. They can commit mutations using context.commit() and can be accessed using context.dispatch().
  • getters: computed properties for getting data from the state.

To use the store in your application, import it into the src/main.js file and add it to the Vue instance.

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

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app');

The Vue instance now includes the store property, which is set to the store instance created in store.js.

Conclusion

In this tutorial, we have covered the basics of building web applications with Vue.js. We created a simple Vue component, implemented Vue Router for handling navigation, and used Vuex for state management. While these are just the basics, Vue.js provides a lot more functionality and flexibility for building complex applications.

By following this tutorial, you should have a good understanding of how to start building web applications with Vue.js. For more advanced topics, refer to the official documentation or the Vue.js community for support.

Related Post