Home Web Development Vue.js 2 and Bootstrap 4 Web Development

Vue.js 2 and Bootstrap 4 Web Development

books-svg-icon Book
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
$10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
BUY NOW $10 p/m for first 3 months. $15.99 p/m after that. Cancel Anytime!
eBook $39.99 $27.98
Print $48.99
Subscription $15.99 $10 p/m for three months
What do you get with a Packt Subscription?
This book & 7000+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook + Subscription?
Download this book in EPUB and PDF formats, plus a monthly download credit
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with a Packt Subscription?
This book & 6500+ ebooks & video courses on 1000+ technologies
60+ curated reading lists for various learning paths
50+ new titles added every month on new and emerging tech
Early Access to eBooks as they are being written
Personalised content suggestions
Customised display settings for better reading experience
50+ new titles added every month on new and emerging tech
Playlists, Notes and Bookmarks to easily manage your learning
Mobile App with offline access
What do you get with eBook?
Download this book in EPUB and PDF formats
Access this title in our online reader
DRM FREE - Read whenever, wherever and however you want
Online reader with customised display settings for better reading experience
What do you get with video?
Download this video in MP4 format
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with video?
Stream this video
Access this title in our online reader
DRM FREE - Watch whenever, wherever and however you want
Online reader with customised display settings for better learning experience
What do you get with Audiobook?
Download a zip folder consisting of audio files (in MP3 Format) along with supplementary PDF
What do you get with Exam Trainer?
Flashcards, Mock exams, Exam Tips, Practice Questions
Access these resources with our interactive certification platform
Mobile compatible-Practice whenever, wherever, however you want
  1. Free Chapter
    Please Introduce Yourself – Tutorial
About this book
In this book, we will build a full stack web application right from scratch up to its deployment. We will start by building a small introduction application and then proceed to the creation of a fully functional, dynamic responsive web application called ProFitOro. In this application, we will build a Pomodoro timer combined with office workouts. Besides the Pomodoro timer and ProFitOro workouts will enable authentication and collaborative content management. We will explore topics such as Vue reactive data binding, reusable components, routing, and Vuex store along with its state, actions, mutations, and getters. We will create Vue applications using both webpack and Nuxt.js templates while exploring cool hot Nuxt.js features such as code splitting and server-side rendering. We will use Jest to test this application, and we will even revive some trigonometry from our secondary school! While developing the app, you will go through the new grid system of Bootstrap 4 along with Vue.js’ directives. We will connect Vuex store to the Firebase real-time database, data storage, and authentication APIs and use this data later inside the application’s reactive components. Finally, we will quickly deploy our application using the Firebase hosting mechanism.
Publication date:
September 2017
Publisher
Packt
Pages
310
ISBN
9781788290920

 

Chapter 1. Please Introduce Yourself – Tutorial

 

Hello, user


Hello dear reader, my name is Olga. Would you like to introduce yourself as well? Open https://pleaseintroduceyourself.xyz/ and leave a message for me and the other readers.

The page itself doesn't look like anything special. It's just a web page that allows users to write a message, and then, this message is immediately displayed along with the other users' messages in a reverse chronological order:

The please introduce yourself page

Do you want to know how long it took me to create this page? It took me around half an hour, and I am not only talking about writing the HTML markup or reversing the order of the messages but also about the database setup, deployment, and hosting.

You probably noticed that the very first message never changes, and it's actually my message where I wrote that I love to learn and teach. This is indeed true. That's why I will devote this chapter to teaching you how to create the exact same page in just 15 minutes. Are you ready? Let's go!

 

Creating a project in the Firebase console


If you still don't have a Google account but you really want to continue with this tutorial, then well, I am really sorry, but you will have to create one this time. Firebase is a service powered by Google, so a Google account is more than required.

If you already have your account, log in to the Firebase console:

https://console.firebase.google.com/.

Let's start by creating your new Firebase project. Click on the Add project button. Give it a meaningful name and select your country from the list. Once you are done, click on CREATE PROJECT:

Create a project using the Firebase console

You're done! Now, you can use the Firebase-powered backend for your application, including a real-time database, authentication mechanism, hosting, and analytics.

Adding a first entry to the Firebase application database

Let's add the first database entry. Click on the Database tab on the left-hand side. You should see a dashboard similar to this one:

Real-time database on the Firebase project dashboard

Let's add an entry called messages and the very first message as a key-value object containing title, text, and timestamp by clicking on the plus sign:

Adding the first value to the Firebase real-time database

Click on the ADD button, and your database will persist the added entry. Add as many message entries as you wish or leave it like that. Now, for the sake of simplicity, let's change the rules of our database and make it readable and writable for everyone. Beware! Never do this for something in production for public usage. In this example, we just want to test some Firebase features, but your future applications must be smart and secure. Click on the RULES tab and type the following rules in the opened text area:

{
  "rules": {
    ".read": true,
    ".write": true
  }
}

So, your RULES tab now looks like this:

Rules tab after changing the rules

Click on the PUBLISH button and you're done! Now, it would be interesting to start using this data within our application. However, first we have to create this application and connect it to our project.

 

Scaffolding a Vue.js application


In this section, we will create a Vue.js application and connect it to the Firebase project that we created in the previous step. Make sure you have Node.js installed on your system.

You must also install Vue.js. Check out the instructions page from the official Vue documentation at https://vuejs.org/v2/guide/installation.html. Alternatively, simply run the npm install command:

$ npm install -g vue-cli

Now, everything is ready to start scaffolding our application. Go to the folder where you want your application to reside and type the following line of code:

vue init webpack please-introduce-yourself

It will ask you several questions. Just choose the default answer and hit Enter for each of them. After the initialization, you are ready to install and run your application:

cd please-introduce-yourself
npm install
npm run dev

If everything is fine, the following page will automatically open in your default browser:

Default Vue.js application after installing and running

If not, check the Vue.js official installation page again.

Connecting the Vue.js application to the Firebase project

To be able to connect your application to the Firebase project, you must install Firebase and VueFire. Run the npm install command while being in the root directory of your new application:

cd please-introduce-yourself
npm install firebase vuefire --save

Now, you can use Firebase's powerful features inside your application. Let's check if it worked! We just have to do the following:

  • Import Firebase

  • Create a config object containing the Firebase app ID, project domain, database domain, and some other stuff needed to connect it to our project

  • Write the code that will use the Firebase API and the created config file to connect to the Firebase project.

  • Use it

Where do we get the necessary information for the configuration of our Firebase instance? Go to the Firebase console, click on the cog to the right of the Overview tab, and select Project Settings. Now, click on the Add Firebase to your web app button:

Click on the Add Firebase to your web app button

A popup with all the information we need will open:

All the information needed for the config object is here

OK, now, just leave this popup open, go to your Vue application, and open the main.js file that resides in the src directory of your application. Here, we need to tell our Vue application that it will use VueFire. In this way, we will be able to use all the features provided by Firebase inside our application. Add the following lines to the import section of the main.js file:

//main.js
import VueFire from 'vuefire'
Vue.use(VueFire)

Great! Now, open the App.vue file. Here, we will import Firebase and initialize our Firebase application inside the Vue application. Add the following lines of code inside the <script> tags:

//App.vue
<script>
  import Firebase from 'firebase'

  let config = {
    apiKey: 'YOUR_API_KEY',
    authDomain: 'YOUR_AUTH_DOMAIN',
    databaseURL: 'YOUR_DATABASE_URL',
    projectId: 'YOUR_PROJECT_ID',
    storageBucket: 'YOUR_STORAGE_BUCKET',
    messagingSenderId: 'YOUR_MESSAGING_SENDER_ID'
  }

  let app = Firebase.initializeApp(config)
</script>

Copy what's needed for the config object information from the popup that we opened in the previous step.

Now, we will obtain the reference to our messages database object. It is pretty simple using the Firebase API:

//App.vue
<script>
  <...>
  let db = app.database()
  let messagesRef = db.ref('messages')
</script>

We're almost done. Now, we just have to export the messages object in the Vue data object so that we are able to use it inside the template section. So, inside the export section, add an entry with the firebase key and point messages to messagesRef:

export default {
  firebase: {
    messages: messagesRef
  },
}

Now, inside the <template> tag, we will use a v-for directive to iterate through the messages array and print all the information about each message. Remember that each message is composed of title, text, and timestamp. So, add the following <div> to the template:

//App.vue
<div v-for="message in messages">
  <h4>{{ message.title }}</h4>
  <p>{{ message.text }}</p>
  <p>{{ message.timestamp }}</p>
</div>

In the end, your App.vue component will look like this:

//App.vue
<template>
  <div id="app">
    <div v-for="message in messages">
      <h4>{{ message.title }}</h4>
      <p>{{ message.text }}</p>
      <p>{{ message.timestamp }}</p>
    </div>
  </div>
</template>

<script>
  import Firebase from 'firebase'

  let config = {
    apiKey: 'YOUR_API_KEY',
    authDomain: 'YOUR_AUTH_DOMAIN',
    databaseURL: 'YOUR_DATABASE_URL',
    projectId: 'YOUR_PROJECT_ID',
    storageBucket: 'YOUR_STORAGE_BUCKET',
    messagingSenderId: 'YOUR_MESSAGING_SENDER_ID'
  }

  let app = Firebase.initializeApp(config)
  let db = app.database()
  let messagesRef = db.ref('messages')
  export default {
    name: 'app',
    firebase: {
      messages: messagesRef
    }
  }
</script>

If you had chosen the default linter settings on the app initialization, the code that you will copy from Firebase and paste into your application will not pass linter. That's because the default linter settings of Vue-cli initialization would require the use of single quotes and no use of semicolon at the end of the line. By the way, Evan You is particularly proud of this no semicolon rule. So, bring him this pleasure; remove all the semicolons from the copied code and replace the double quotes with single quotes.

Aren't you curious to check out the page? If you are not running your application already, switch inside the application folder and run it:

cd please-introduce-yourself
npm run dev

I am pretty sure that you are seeing the following screenshot:

The Vue.js web application displaying the information from the Firebase database

Congratulations! You have successfully completed the first part of our tutorial, connecting the Vue.js application to the Firebase real-time database.

 

Adding a Bootstrap-powered markup


Let's add basic styling to our application by adding Bootstrap and using its classes.

First of all, let's include Bootstrap's CSS and JS files from Bootstrap's CDN. We will use the upcoming version 4, which is still in alpha. Open the index.html file and add the necessary link and script tags inside the <head> section:

//index.html
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css"crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.min.js"crossorigin="anonymous"></script>
<script src="https://npmcdn.com/tether@1.2.4/dist/js/tether.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"crossorigin="anonymous">
</script>

You've probably noticed that I added jQuery and Tether dependencies as well; this is because Bootstrap depends on them.

Now, we can use Bootstrap classes and components in our application. Let's start by adding a bit of styling using Bootstrap's classes.

I will wrap the whole app div tag into the jumbotron class, and then, I will wrap the content of it into the container class. So, the template will look a bit different:

//App.vue
<template>
  <div id="app" class="jumbotron">
    <div class="container">
      <h1>Hello! Nice to meet you!</h1>
    <hr />
    <div v-for="message in messages">
    <...>
    </div>
  </div>
</div>
</template>

Check out the page; doesn't it look different? Now, I would like to wrap up the content of each message into the card class. Cards seem to be an appropriate container for this kind of things. Check out the official Bootstrap documentation regarding cards at https://v4-alpha.getbootstrap.com/components/card/. I will add div tag with a card-group class and put all the cards with messages inside this container. Thus, I don't need to be worried about the positioning and layout. Everything becomes responsive just by itself! So, the markup for the messages will look like this:

//App.vue
<template>
<...>
  <div class="card-group">
    <div class="card" v-for="message in messages">
      <div class="card-block">
        <h5 class="card-title">{{ message.title }}</h5>
        <p class="card-text">{{ message.text }}</p>
        <p class="card-text"><small class="text-muted">Added on {{ message.timestamp }}</small></p>
      </div>
    </div>
  </div>
</template>

Check out the page. It's almost looking nice! In a few steps, we were able to nicely display the messages that are stored in our Firebase database. Try to add another message using the Firebase real-time database dashboard. Keep the web page open! Fill in the Firebase database fields:

Adding an entry to the Firebase database

Now, click on the ADD button. The new message automatically appears on your web page:

Once we click on the ADD button, the new message immediately appears on our web page

Isn't it great? Now, we can add as many messages as we want. We can also delete them and manipulate them, and all changes will be automatically propagated to our web page. This is pretty nice, but do we really want to keep playing with our backend database to see something changing on the web page? Of course, not! We want the users of our page to be able to add their messages using our page and not our database dashboard. Let's go back to our Vue.js application and add a form that will allow us to add new messages.

Adding a form using Bootstrap

Let's add a simple form to our application that will enable us to add new messages to our message board. Check Bootstrap's documentation regarding forms at https://v4-alpha.getbootstrap.com/components/forms/.

Let's add a form just before the list of messages. This form will contain the input for the title, the text area for the message, and the submit button. It will look like this:

//App.vue
<template>
  <div id="app" class="jumbotron">
    <div class="container">
      <h1>Hello! Nice to meet you!</h1>
      <hr />
      <form>
        <div>
          <input maxlength="40" autofocus placeholder="Please introduce yourself :)" />
        </div>
        <div>
          <textarea placeholder="Leave your message!"  rows="3">
          </textarea>
        </div>
        <button type="submit">Send</button>
      </form>
      <hr />
      <...>
    </div>
  </div>
</template>

Look at the page. Doesn't look that beautiful, does it?

Our form doesn't look so beautiful

In fact, let's be honest, it just looks ugly! However, with Bootstrap classes, it is really easy to fix it. If we add the form-control class to the input and textarea elements, the form-group class to each div tag that surrounds these elements, and probably the btn btn-primary class to the submit button…well, we will have something nicer!

The form looks really nice with the Bootstrap classes

OK, so now we have a nice-looking form, but if we try to fill it out, nothing will happen. We have to make it functional, and for that, we will use the power of Vue.js.

 

Making things functional with Vue.js


So, what do we want to achieve with our form? We want the new message to be created. This message has to be composed of title, text, and the timestamp. We also want to add this message to our messages reference array.

Let's call this new message newMessage and add it to the data attributes of App.vue:

//App.vue
<script>
  <...>
  export default {
    data () {
      return {
        newMessage: {
          title: '',
          text: '',
          timestamp: null
        }
      }
    },
  <...>
  }
</script>

Now, let's bind the title and the text of this newMessage object to input and textarea of our form. Let's also bind a method called addMessage to the submit handler of our form so that the whole form's markup looks like this:

<template>
<...>
  <form @submit="addMessage">
    <div class="form-group">
      <input class="form-control"v-model="newMessage.title"maxlength="40"autofocus  placeholder="Please introduce yourself :)" />
    </div>
    <div class="form-group">
      <textarea class="form-control"v-model="newMessage.text" placeholder="Leave your message!"  rows="3"></textarea>
    </div>
    <button class="btnbtn-primary" type="submit">Send</button>
  </form>
  <...>
</template>

Well, we have bound the "addMessage" method to the submit callback of the form, but we haven't defined this method yet! So, let's define it. Add the methods object to our App.vue export section and define the addMessage method inside it. This method will receive the event attribute from our form and will just grab the newMessage object and push it into the messagesRef array. Doesn't it sound easy?

//App.vue
<script>
  export default {
  <...>
    methods: {
      addMessage (e) {
        e.preventDefault()
        this.newMessage.timestamp = Date.now()
        messagesRef.push(this.newMessage)
      }
    }
  }
</script>

Now, open the page, fill in the form, and hit the Send button. You'll see your message immediately appearing on the list of messages:

The message we introduce in the form is immediately propagated to the messages list

There is still something we need to fix. We don't want the values we fill the form with to remain there after our message is added to the messages list. So, we need to clear it inside the addMessage method. Probably, some basic check, at least for the title, would also be nice. So, rewrite the method as follows:

//App.vue
addMessage (e) {
  e.preventDefault()
  if (this.newMessage.title === '') {
    return
  }
  this.newMessage.timestamp = Date.now()
  messagesRef.push(this.newMessage)
  this.newMessage.text = ''
  this.newMessage.title = ''
  this.newMessage.timestamp = null
}

Now, if you start adding more messages, things look a bit weird. The way we're displaying the messages is probably not the best way for our case. Do you remember we wrapped up our message cards into div with the card-group class? Let's try to replace it with the card-columns class and check whether it looks better. In fact, it does. Let's keep it like that.

Adding utility functions to make things look nicer

We already have a fully functional single-page application, but it still lacks some awesomeness. For example, it's not really beautiful that the time appears as a timestamp. Let's write the utility function that will transform our timestamp into something beautiful.

We will use the Moment.js library (https://momentjs.com/). Install it in the application folder:

npm install moment --save

Create a folder and call it utils. Add a file called utils.js to this folder. Import moment and write the following function:

//utils.js
import moment from 'moment'

function dateToString (date) {
  if (date) {
    return moment(date).format('MMMM Do YYYY, h:mm:ss a')
  }
  return''
}

Export it in the end of the file:

//utils.js
<...>
export { dateToString }

Let's import this function to App.vue and use it to format our timestamp. Open the App.vue file and add the import statement at the beginning of the script section:

//App.vue
<script>
  import Firebase from 'firebase'
  import { dateToString } from './utils/utils'
  <...>
</script>

In order to be able to use this function within the Vue template, we have to export it in the methods section. Just add a new entry to the methods object:

//App.vue
<script>
  export default {
    <...>
    methods: {
      dateToString: dateToString,
      <...>
    }
</script>

Since we use ES6, we can just write the following lines of code:

methods: {
  dateToString
}

Now, we can use this method inside the template section. Just wrap the message.timestamp binding object in the dataToString method:

<p class="card-text"><small class="text-muted">Added on {{ dateToString(message.timestamp) }}</small></p>

Check out the page! Now, you can see beautiful dates instead of Unix timestamps.

Exercise

I have a small exercise for you. You saw how easy it was to add a utility function to transform the timestamp into the nicely formatted date. Now, create another utility function and call it reverse. This function should be used to display the array of messages in the reversed order, so the most recent messages should appear first. Check the code for this chapter in case you're in doubt.

Extracting message cards to their own component

You probably noticed that the first message of the demo application is always there. It's not moved by other, fresh message items. So, it seems that it's kind of a special message, and it's treated in a special way. In fact, it is. If you want to make a card sticky, just add it before the card element that iterates through other messages. You can also add some class to this card to show that it's really special. In my case, I added Bootstrap's card-outline-success class that outlines the element in a nice green color:

//App.vue
<div class="card-columns">
  <div class="card card-outline-success">
    <div class="card-block">
      <h5 class="card-title">Hello!</h5>
      <p class="card-text">This is our fixed card!</p>
      <p class="card-text"><small class="text-muted">Added on {{ dateToString(Date.now()) }}</small></p>
    </div>
  </div>
  <div class="card" v-for="message in messages">
    <div class="card-block">
      <h5 class="card-title">{{ message.title }}</h5>
      <p class="card-text">{{ message.text }}</p>
      <p class="card-text"><small class="text-muted">Added on {{ dateToString(message.timestamp) }}</small></p>
    </div>
  </div>
</div>

Now, you have a nice sticky card with a color that differs from other cards' color. But… don't you see any problem? We have the very same code repeated twice in our template. I'm pretty sure that you are aware of the rule of thumb of any developer: DRY—don't repeat yourself!

Let's extract the card to an individual component. It's really easy. Add a component called Card.vue to the components folder. The code for this component is really simple:

//Card.vue
<template>
  <div class="card">
    <div class="card-block">
      <h5 class="card-title">{{ title }}</h5>
      <p class="card-text">{{ text }}</p>
      <p class="card-text"><small class="text-muted">{{ footer }}</small></p>
    </div>
  </div>
</template>

<script>
  export default {
    props: ['title', 'text', 'footer']
  }
</script>

Now, let's invoke this component from App.vue with different values for title, text, and footer. First of all, it should be imported and exported in the Vue components object:

//App.vue
<script>
<...>
  import Card from './components/Card'
  <...>
  export default {
  <...>
    components: {
      Card
    }
  }
</script>

Now, we can use the <card> element within our template. We need to bind title, text, and footer. Footer is actually the text that says Added on …. So, the markup for the first card will look like this:

//App.vue
<template>
  <div class="card-columns">
    <card class="card-outline-success":title="'Hello!'":text="'This is our fixed card!'":footer="'Added on ' + dateToString(Date.now())"></card>
  </div>
</div>
</template>

The list of other messages will follow the same logic. For each message from the messages array, we will bind the corresponding message's entries (title, text, and timestamp). So, the markup for the list of message cards will look like this:

<div class="card-columns">
<...>
  <card v-for="message in messages":title="message.title":text="message.text":footer="'Added on ' + dateToString(message.timestamp)"></card>
</div>
</div>

As you can see, we have replaced fourteen lines of code with only two lines! Of course, our component also contains some lines of code, but now, we can reuse it again and again.

Exercise

The way we've extracted the card code into its individual component is, without any doubt, great, but the way we are binding attributes for the first message is a bit ugly. What if at some point we need to change the message's text? First of all, it's not easy to find the text inside the markup. Also, it is pretty difficult to manage the text inside the markup attributes, because we have to be really careful not to mess up with double/single quotes. And, admit it, it's just ugly. Your task for this exercise is to extract title, text, and date for the first message into something nicer (for example, export it in the data object) and bind it the same way we bind other messages. If you have doubts regarding this exercise, check out this chapter's code.

Note

Don't be confused by the v-bind directive in the provided code. We've been using it already, just its shortened version—the name of a bound property written after the semicolon. So, for example, v-bind:messages is the same as :messages.

 

Deploying your application


Well, now that we have a fully working application in our hands, it's time to make it public. In order to do this, we will deploy it to Firebase.

Start by installing Firebase tools:

npm install -g firebase-tools

Now, you have to tell your Firebase tools that you are actually a Firebase user who has an account. For this, you have to log in using Firebase tools. Run the following command:

firebase login

Follow the instructions to log in.

Now, you must initialize Firebase in your application. From the application root, call the following:

firebaseinit

You will be asked some questions. Select the third option for the first question:

Select the Hosting option for the first question

Select the PleaseIntroduceYourself project from the list of projects to associate to the application.

Initialization is over. Check whether the file called firebase.json has been created in the project's folder. This file can contain an innumerous number of configurations. Check out the official Firebase documentation in this regard at https://firebase.google.com/docs/hosting/full-config. For us, the very basic indication of the public directory to be deployed would be enough. The directory where vue-cli builds the production-ready assets is called dist; therefore, we will want the content of this directory to be deployed. So, add the following line of code to your firebase.json file:

{
  "hosting": {
    "public": "dist",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ]
  }
}

Do not forget to save your firebase.json file. Let's now build and deploy our application. Sounds like a big devops task, right? It's not really huge. Run npm build and then firebase deploy:

npm run build
firebase deploy

How difficult is it? After the successful deployment, Firebase will output the URL of your project. Now, you can start playing with it and send it to your friends. It's probably not the most beautiful URL in the world, right? Maybe you would like to connect it to your domain? Of course, it is possible!

 

Extra mile – connecting your Firebase project to a custom domain


It's fairly easy to connect the Firebase project to a custom domain. First of all, of course, you need to buy this domain. For this application, I bought the pleaseintroduceyourself domain with the cheapest top-level domain, .xyz. It cost me a bit more than a dollar per year on GoDaddy (https://godaddy.com). After you have your domain, it's really easy. Go to the Firebase web console of the project. Click on the Hosting tab on the left-hand side. Then, click on the CONNECT DOMAIN button:

Click on the CONNECT DOMAIN button

In the popup, input your domain name:

Input your domain name

It will suggest that you add a TXT DNS record to your domain. Just open your DNS provider page, select your domain, find out how to add DNS records, and add the record with the TXT type. In my case, with GoDaddy, the record adding section looks like this:

Adding the DNS TXT record to our domain

After the handshake is established (mind, it might take some time), Firebase will propose you the final step—adding the A record to your domain. Follow the exact same procedure as in the previous step; just instead of records of type TXT, add records of type A.

It will take some time until the changes are completely propagated. In my case, it took around an hour. After a while, you will be able to open your new page with the https://<your domain>.<your top level domain> address. In my case, as you already know, it's https://pleaseintroduceyourself.xyz/.

 

Summary


In this chapter, we followed a tutorial where we have developed a single-page application from scratch. We used the Vue.js framework to structure our application, the Bootstrap framework to apply style to it, and the Firebase platform to manage the application's persistence layer and hosting.

In spite of being able to achieve a considerable result (a fully functional deployed application), we did everything without a deep understanding of what is going on behind the scenes. The tutorial didn't explain what Vue.js, Bootstrap, or Firebase was. We just took it for granted.

In the next chapter, we will understand the underlying technologies in detail. We will do the following:

  • Take a closer look at the Vue.js framework, starting from a basic understanding and then covering topics such as directives, data binding, components, routing, and so on

  • Have a deeper look at the Bootstrap framework, and check what is possible to achieve using it and how to do it

  • Get to know the Firebase platform better; we'll gain some basic understanding about it and go through more complex topics such as data storage or functions

  • Check out different techniques to use these three different projects to add simplicity, power, and flexibility to our applications

Latest Reviews (3 reviews total)
To be honest....starting off showing other plugs and software you need before ....is not very wise. I might have been wrong but the title does say, VueJS and Bootstrap, so why not sticking with that??
These books are really useful
All purchases I have done with PacktPub were great, easy to choose the books or videos and the purchasing process is quite easy. I just would suggest that there was a warning when you are trying to buy a book you already own.
Vue.js 2 and Bootstrap 4 Web Development
Unlock this book and the full library FREE for 7 days
Start now