Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Full-Stack Vue.js 2 and Laravel 5
Full-Stack Vue.js 2 and Laravel 5

Full-Stack Vue.js 2 and Laravel 5: Bring the frontend and backend together with Vue, Vuex, and Laravel

Arrow left icon
Profile Icon Anthony Gore
Arrow right icon
$27.98 $39.99
Book Dec 2017 376 pages 1st Edition
eBook
$27.98 $39.99
Print
$48.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Anthony Gore
Arrow right icon
$27.98 $39.99
Book Dec 2017 376 pages 1st Edition
eBook
$27.98 $39.99
Print
$48.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$27.98 $39.99
Print
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Full-Stack Vue.js 2 and Laravel 5

Chapter 1. Hello Vue – An Introduction to Vue.js

Welcome to Full-Stack Vue.js 2 and Laravel 5! In this first chapter, we'll take a high-level overview of Vue.js, getting you familiar with what it can do, in preparation for learning how to do it.

We'll also get acquainted with Vuebnb, the main case-study project featured in this book.

Topics this chapter covers:

  • Basic features of Vue, including templates, directives, and components
  • Advanced features of Vue including single-file components and server-side rendering
  • Tools in the Vue ecosystem including Vue Devtools, Vue Router, and Vuex
  • The main case-study project that you'll be building as you progress through the book, Vuebnb
  • Instructions for installing the project code

Introducing Vue.js


At the time of writing in late 2017, Vue.js is at version 2.5. In less than four years from its first release, Vue has become one of the most popular open source projects on GitHub. This popularity is partly due to its powerful features, but also to its emphasis on developer experience and ease of adoption.

The core library of Vue.js, like React, is only for manipulating the view layer from the MVC architectural pattern. However, Vue has two official supporting libraries, Vue Router and Vuex, responsible for routing and data management respectively.

Vue is not supported by a tech giant in the way that React and Angular are and relies on donations from a small number of corporate patrons and dedicated Vue users. Even more impressively, Evan You is currently the only full-time Vue developer, though a core team of 20 more developers from around the world assist with development, maintenance, and documentation.

The key design principles of Vue are as follows:

  • Focus: Vue has opted for a small, focused API, and its sole purpose is the creation of UIs
  • Simplicity: Vue's syntax is terse and easy to follow
  • Compactness: The core library script is ~25 KB minified, making it smaller than React and even jQuery
  • Speed: Rendering benchmarks beat many of the main frameworks, including React
  • Versatility: Vue works well for small jobs where you might normally use jQuery, but can scale up as a legitimate SPA solution

Basic features


Let's now do a high-level overview of Vue's basic features. If you want, you can create an HTML file on your computer like the following one, open it in your browser, and code along with the following examples.

If you'd rather wait until the next chapter, when we start working on the case-study project, that's fine too as our objective here is simply to get a feel for what Vue can do:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title>Hello Vue</title>
</head>
<body>
  <!--We'll be adding stuff here!-->
</body>
</html>

Installation

Although Vue can be used as a JavaScript module in more sophisticated setups, it can also simply be included as an external script in the body of your HTML document:

<script src="https://unpkg.com/vue/dist/vue.js"></script>

Templates

By default, Vue will use an HTML file for its template. An included script will declare an instance of Vue and use the el property in the configuration object to tell Vue where in the template the app will be mounted:

<div id="app">
  <!--Vue has dominion within this node-->
</div>
<script>
  new Vue({
    el: '#app'
  });
</script>

We can bind data to our template by creating it as a data property and using the mustache syntax to print it in the page:

<div id="app">
  {{ message }}
  <!--Renders as "Hello World"-->
</div>
<script>
  new Vue({
    el: '#app',
    data: {
      message: 'Hello World'
    }
  });
</script>

Directives

Similar to Angular, we can add functionality to our templates by using directives. These are special properties we add to HTML tags starting with the v- prefix.

Say we have an array of data. We can render this data to the page as sequential HTML elements by using the v-for directive:

<div id="app">
  <h3>Grocery list</h3>
  <ul>
    <li v-for="grocery in groceries">{{ grocery }}</li>
  </ul>
</div>
<script>
  var app = new Vue({
    el: '#app',
    data: {
      groceries: [ 'Bread', 'Milk' ]
    }
  });
</script>

The preceding code renders as follows:

<div id="app">
  <h3>Grocery list</h3>
  <ul>
    <li>Bread</li>
    <li>Milk</li>
  </ul>
</div>

Reactivity

A key feature of Vue's design is its reactivity system. When you modify data, the view automatically updates to reflect that change.

For example, if we create a function that pushes another item to our array of grocery items after the page has already been rendered, the page will automatically re-render to reflect that change:

setTimeout(function() {
  app.groceries.push('Apples');
}, 2000);

Two seconds after the initial rendering, we see this:

<div id="app">
  <h3>Grocery list</h3>
  <ul>
    <li>Bread</li>
    <li>Milk</li>
    <li>Apples</li>
  </ul>
</div>

Components

Components extend basic HTML elements and allow you to create your own reusable custom elements.

For example, here I've created a custom element, grocery-item, which renders as a li. The text child of that node is sourced from a custom HTML property, title, which is accessible from within the component code:

<div id="app">
  <h3>Grocery list</h3>
  <ul>
    <grocery-item title="Bread"></grocery-item>
    <grocery-item title="Milk"></grocery-item>
  </ul>
</div>
<script>
  Vue.component( 'grocery-item', { 
    props: [ 'title' ],
    template: '<li>{{ title }}</li>'
  });

  new Vue({
    el: '#app'
  });
</script>

This renders as follows:

<div id="app">
  <h3>Grocery list</h3>
  <ul>
    <li>Bread</li>
    <li>Milk</li>
  </ul>
</div>

But probably the main reason to use components is that it makes it easier to architect a larger application. Functionality can be broken into reuseable, self-contained components.

Advanced features


If you have been coding along with the examples so far, close your browser now until next chapter, as the following advanced snippets can't simply be included in a browser script.

Single-file components

A drawback of using components is that you need to write your template in a JavaScript string outside of your main HTML file. There are ways to write template definitions in your HTML file, but then you have an awkward separation between markup and logic.

A convenient solution to this is single-file components:

<template>
  <li v-on:click="bought = !bought" v-bind:class="{ bought: bought }">
    <div>{{ title }}</div>
  </li>
</template>
<script>
  export default {
    props: [ 'title' ],
    data: function() {
      return {
        bought: false
      };
    }
  }
</script>
<style>
  .bought {
    opacity: 0.5;
  }
</style>

These files have the .vue extension and encapsulate the component template, JavaScript configuration, and style all in a single file.

Of course, a web browser can't read these files, so they need to be first processed by a build tool such as Webpack.

Module build

As we saw earlier, Vue can be dropped into a project as an external script for direct use in a browser. Vue is also available as an NPM module for use in more sophisticated projects, including a build tool such as Webpack.

If you're unfamiliar with Webpack, it's a module bundler that takes all your project assets and bundles them up into something you can provide to the browser. In the bundling process, you can transform those assets as well.

Using Vue as a module and introducing Webpack opens possibilities such as the following:

  • Single-file components
  • ES feature proposals not currently supported in browsers
  • Modularized code
  • Pre-processors such as SASS and Pug

Note

We will be exploring Webpack more extensively in Chapter 5Integrating Laravel and Vue.js with Webpack.

Server-side rendering

Server-side rendering is a great way to increase the perception of loading speed in full-stack apps. Users get a complete page with visible content when they load your site, as opposed to an empty page that doesn't get populated until JavaScript runs.

Say we have an app built with components. If we use our browser development tool to view our page DOM after the page has loaded, we will see our fully rendered app:

<div id="app">
  <ul>
    <li>Component 1</li>
    <li>Component 2</li>
    <li>
      <div>Component 3</div>
    </li>
  </ul>
</div>

But if we view the source of the document, that is, index.html, as it was when sent by the server, you'll see it just has our mount element:

<div id="app"></div>

Why? Because JavaScript is responsible for building our page and, ipso facto, JavaScript has to run before the page is built. But with server-side rendering, our index file includes the HTML needed for the browser to build a DOM before JavaScript is downloaded and run. The app does not load any faster, but content is shown sooner.

The Vue ecosystem


While Vue is a standalone library, it is even more powerful when combined with some of the optional tools in its ecosystem. For most projects, you'll include Vue Router and Vuex in your frontend stack, and use Vue Devtools for debugging.

Vue Devtools

Vue Devtools is a browser extension that can assist you in the development of a Vue.js project. Among other things, it allows you to see the hierarchy of components in your app and the state of components, which is useful for debugging:

Figure 1.1. Vue Devtools component hierarchy

We'll see what else it can do later in this section.

Vue Router

Vue Router allows you to map different states of your SPA to different URLs, giving you virtual pages. For example, mydomain.com/ might be the front page of a blog and have a component hierarchy like this:

<div id="app">
  <my-header></my-header>
  <blog-summaries></blog-summaries>
  <my-footer></my-footer>
</div>

Whereas mydomain.com/post/1 might be an individual post from the blog and look like this:

<div id="app">
  <my-header></my-header>
  <blog-post post-id="id">
  <my-footer></my-footer>
</div>

Changing from one page to the other doesn't require a reload of the page, just swapping the middle component to reflect the state of the URL, which is exactly what Vue Router does.

Vuex

Vuex provides a powerful way to manage the data of an application as the complexity of the UI increases, by centralizing the application's data into a single store.

We can get snapshots of the application's state by inspecting the store in Vue Devtools:

Figure 1.2. Vue Devtools Vuex tab

The left column tracks changes made to the application data. For example, say the user saves or unsaves an item. You might name this event toggleSaved. Vue Devtools lets you see the particulars of this event as it occurs.

We can also revert to any previous state of the data without having to touch the code or reload the page. This function, called Time Travel Debugging, is something you'll find very useful for debugging complex UIs.

Case-study project


After a whirlwind overview of Vue's key features, I'm sure you're keen now to start properly learning Vue and putting it to use. Let's first have a look at the case-study project you'll be building throughout the book.

Vuebnb

Vuebnb is a realistic, full-stack web application which utilizes many of the main features of Vue, Laravel, and the other tools and design patterns covered in this book.

From a user's point of view, Vuebnb is an online marketplace for renting short-term lodgings in cities around the world. You may notice some likeness between Vuebnb and another online marketplace for accommodation with a similar name!

You can view a completed version of Vuebnb here: http://vuebnb.vuejsdevelopers.com.

If you don't have internet access right now, here are screenshots of two of the main pages. Firstly, the home page, where users can search or browse through accommodation options:

Figure 1.3. Vuebnb home page

Secondly, the listing page, where users view information specific to a single lodging they may be interested in renting:

Figure 1.4. Vuebnb listing page

Code base

The case-study project runs through the entire duration of this book, so once you've created the code base you can keep adding to it chapter by chapter. By the end, you'll have built and deployed a full-stack app from scratch.

The code base is in a GitHub repository. Download it in whatever folder on your computer that you normally put projects in, for example, ~/Projects:

$ cd ~/Projects
$ git clone https://github.com/PacktPublishing/Full-Stack-Vue.js-2-and-Laravel-5
$ cd Full-Stack-Vue.js-2-and-Laravel-5

Note

Rather than cloning this repository directly, you could first make a fork and clone that. This will allow you to make any changes you like and save your work to your own remote repository. Here's a guide to forking a repository on GitHub: https://help.github.com/articles/fork-a-repo/.

Folders

The code base contains the following folders:

Figure 1.5. Code base directory contents

Here's a rundown of what each folder is used for:

  • Chapter02 to Chapter10 contains the completed state of the code for each chapter (excluding this one)
  • The images directory contains sample images for use in Vuebnb. This will be explained in Chapter 4Building a Web Service with Laravel
  • vuebnb is the project code you'll use for the main case-study project that we begin work on in Chapter 3Setting Up a Laravel Development Environment
  • vuebnb-prototype is the project code of the Vuebnb prototype that we'll build in Chapter 2Prototyping Vuebnb, Your First Vue.js Project

Summary


In this first chapter, we did a high-level introduction to Vue.js, covering the basic features such as templates, directives, and components, as well as advanced features such as single-file components and server-side rendering. We also had a look at the tools in Vue's ecosystem including Vue Router and Vuex.

We then did an overview of Vuebnb, the full-stack project that you'll be building as you progress through the book, and saw how to install the code base from GitHub.

In the next chapter, we'll get properly acquainted with Vue's basic features and starting putting them to use by building a prototype of Vuebnb.

 

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • End-to-end guide on full-stack development with Vue.js 2 and Laravel 5
  • Developing modern user interfaces with a reusable component-based architecture
  • Use Webpack to improve applications performance and development workflow
  • Explore the features of Vuex to build applications that are powerful, consistent, and maintainable

Description

Vue is a JavaScript framework that can be used for anything from simple data display to sophisticated front-end applications and Laravel is a PHP framework used for developing fast and secure web-sites. This book gives you practical knowledge of building modern full-stack web apps from scratch using Vue with a Laravel back end. In this book, you will build a room-booking website named "Vuebnb". This project will show you the core features of Vue, Laravel and other state-of-the-art web development tools and techniques. The book begins with a thorough introduction to Vue.js and its core concepts like data binding, directives and computed properties, with each concept being explained first, then put into practice in the case-study project. You will then use Laravel to set up a web service and integrate the front end into a full-stack app. You will be shown a best-practice development workflow using tools like Webpack and Laravel Mix. With the basics covered, you will learn how sophisticated UI features can be added using ES+ syntax and a component-based architecture. You will use Vue Router to make the app multi-page and Vuex to manage application state. Finally, you will learn how to use Laravel Passport for authenticated AJAX requests between Vue and the API, completing the full-stack architecture. Vuebnb will then be prepared for production and deployed to a free Heroku cloud server.

What you will learn

  • Use the Core features of Vue.js to create sophisticated user interfaces
  • Build a secure backend API with Laravel
  • Learn a state-of-the-art web development workflow with Webpack
  • Learn about full-stack app design principles and best practices
  • Learn to deploy a full-stack app toa cloud server and CDN
  • Manage complex application state with Vuex
  • Secure a web service with Laravel Passport

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Dec 28, 2017
Length 376 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781788299589

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want

Product Details

Publication date : Dec 28, 2017
Length 376 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781788299589

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together

Stars icon
Total $ 85.95 123.97 38.02 saved
Full-Stack Vue.js 2 and Laravel 5
$27.98 $39.99
Vue.js 2.x by Example
$29.99 $43.99
Vue.js 2 Design Patterns and Best Practices
$27.98 $39.99
=
Book stack Total $ 85.95 123.97 38.02 saved Stars icon

Table of Contents

18 Chapters
Title Page Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
About the Reviewer Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Customer Feedback Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
1. Hello Vue – An Introduction to Vue.js Chevron down icon Chevron up icon
2. Prototyping Vuebnb, Your First Vue.js Project Chevron down icon Chevron up icon
3. Setting Up a Laravel Development Environment Chevron down icon Chevron up icon
4. Building a Web Service with Laravel Chevron down icon Chevron up icon
5. Integrating Laravel and Vue.js with Webpack Chevron down icon Chevron up icon
6. Composing Widgets with Vue.js Components Chevron down icon Chevron up icon
7. Building a Multi-Page App with Vue Router Chevron down icon Chevron up icon
8. Managing Your Application State with Vuex Chevron down icon Chevron up icon
9. Adding a User Login and API Authentication with Passport Chevron down icon Chevron up icon
10. Deploying a Full-Stack App to the Cloud Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.