Full-Stack Vue.js 2 and Laravel 5 - Anthony Gore - E-Book

Full-Stack Vue.js 2 and Laravel 5 E-Book

Anthony Gore

0,0
41,99 €

-100%
Sammeln Sie Punkte in unserem Gutscheinprogramm und kaufen Sie E-Books und Hörbücher mit bis zu 100% Rabatt.

Mehr erfahren.
Beschreibung

Learn to build professional full-stack web apps with Vue.js and Laravel

About This Book

  • 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

Who This Book Is For

This book targets developers who are new to Vue.js, Laravel, or both, and are seeking a practical, best-practice approach to development with these technologies.

They must have some knowledge of HTML, CSS and Javascript.

What You Will Learn

  • 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
  • Full-stack app design principles and best practices
  • Learn to deploy a full-stack app to a cloud server and CDN
  • Managing complex application state with Vuex
  • Securing a web service with Laravel Passport

In Detail

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.

Style and approach

Learn front-end Vue techniques, back-end Laravel skills, and put them together to build a working application

Sie lesen das E-Book in den Legimi-Apps auf:

Android
iOS
von Legimi
zertifizierten E-Readern

Seitenzahl: 337

Veröffentlichungsjahr: 2017

Bewertungen
0,0
0
0
0
0
0
Mehr Informationen
Mehr Informationen
Legimi prüft nicht, ob Rezensionen von Nutzern stammen, die den betreffenden Titel tatsächlich gekauft oder gelesen/gehört haben. Wir entfernen aber gefälschte Rezensionen.



Full-Stack Vue.js 2 and Laravel 5

                   

 

Bring the frontend and backend together with Vue, Vuex, and Laravel

                   

 

 

Anthony Gore

 

 

 

BIRMINGHAM - MUMBAI

Full-Stack Vue.js 2 and Laravel 5

 

Copyright © 2017 Packt Publishing

 

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

 

First published: December 2017

Production reference: 1261217

 

Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.

ISBN  978-1-78829-958-9

 

www.packtpub.com

Credits

Author

Anthony Gore

Copy Editor

Safis Editing

Reviewer

Ashley Menhennett

Project Coordinator

Hardik Bhinde

Commissioning Editor

Kunal Chaudhari

Proofreader

Safis Editing

Acquisition Editor

Siddharth Mandal

Indexer

Tejal Daruwale Soni

ContentDevelopmentEditor

Mohammed Yusuf Imaratwale

Graphics

Tania Dutta

Technical Editor

Harshal Kadam

Production Coordinator

Shantanu Zagade

About the Author

Anthony Gore is a full-stack web developer from Sydney, Australia. He loves to share knowledge about web technologies, with a particular passion for JavaScript.

Anthony is the founder of Vue.js Developers, the largest online community of Vue enthusiasts, and he curates the weekly Vue.js Developers Newsletter. He is also a frequent blogger and the author of Ultimate Vue.js Developers Video Course.

Besides web development, Anthony is a keen musician and is often traveling abroad and working remotely.

I would like to thank my parents, Graeme and Paula, for encouraging me to follow my interests and passions and for their love and support while I worked on this book.

About the Reviewer

Ashley Menhennett is a developer from South Australia, with 6 years of experience in web and software development, thriving on solving real-world problems through the application of software engineering processes. Ashley has recently accepted an offer of a graduate position in platform engineering, with plans to continue future study in the field of computer science. Ashley enjoys spending time with family and his Jack Russell, Alice.

With thanks to my friends and family for their support.

www.PacktPub.com

For support files and downloads related to your book, please visit www.PacktPub.com. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.

At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

https://www.packtpub.com/mapt

Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.

Why subscribe?

Fully searchable across every book published by Packt

Copy and paste, print, and bookmark content

On demand and accessible via a web browser

Customer Feedback

Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1788299582.

If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!

Table of Contents

Preface

What this book covers

What you need for this book

Operating system

Development tools

Browser

Vue Devtools

IDE

Hardware

Who this book is for

Conventions

Reader feedback

Customer support

Downloading the example code

Errata

Piracy

Questions

Hello Vue – An Introduction to Vue.js

Introducing Vue.js

Basic features

Installation

Templates

Directives

Reactivity

Components

Advanced features

Single-file components

Module build

Server-side rendering

The Vue ecosystem

Vue Devtools

Vue Router

Vuex

Case-study project

Vuebnb

Code base

Folders

Summary

Prototyping Vuebnb, Your First Vue.js Project

Vuebnb prototype

Project code

NPM install

Main files

Opening in the browser

Installing Vue.js

Page content

The Vue instance

Data binding

Mock listing

Header image

Style binding

Directives

Usage

Expressions

Example: v-if

Arguments

Style binding (continued)

Lists section

List rendering

Icons

Key

Prices

Show more feature

Class binding

Event listener

Reactivity

Getters and setters

Reactive data properties

Hiding the More button

Image modal window

Opening

Window

Disabling the main window

Dimming the main window

Preventing body scroll

Vue's mount element

Watchers

Closing

Escape key

Event modifiers

Lifecycle hooks

Methods

Proxied properties

Removing listener

Summary

Setting Up a Laravel Development Environment

Laravel

Laravel and Vue

Environment

Homestead

Vuebnb

Project code

Shared folders

Terminal commands

Environment variables

Composer install

Database

Serving the project

Local DNS entry

Accessing the project

Summary

Building a Web Service with Laravel

Vuebnb room listings

Web service

Mock data

Database

Migration

Schema

Execution

Seeding mock listings

Creating a seeder

Loading the mock data

Inserting the data

Executing the seeder

Listing model

Eloquent ORM

Casting

Public interface

Controller

Images

Accessing images

Image links

Summary

Integrating Laravel and Vue.js with Webpack

Laravel frontend

JavaScript

CSS

Node modules

Views

Asset compilation

Webpack

Dependencies

Modules

Bundling

Loaders

Laravel Mix

Running Webpack

CLI

First build

JavaScript

CSS

Fonts

Migrating Vuebnb

Removing unnecessary dependencies and files

HTML

Syntax clash

JavaScript

Mock data dependency

Displaying modules with Webpack

Vue.js dependency

CSS

Font styles

Fonts

Images

Development tools

Watch mode

BrowserSync

ES2015

Polyfills

Mock data

Routes

Architecture

Injecting data

JSON

Sharing data between scripts

Replacing the hard-coded model

Amenities and prices

Image URLs

Replacing the hard-coded image URLs

Summary

Composing Widgets with Vue.js Components

Components

Registration

Data

Image carousel

Changing images

Computed properties

Composing with components

Registration scope

Carousel controls

Communicating with components

Props

One-way data flow

Dynamic props

Image URLs

Distinguishing carousel controls

Custom events

Changing carousel images

Single-file components

Transformation

Refactoring components to SFCs

CSS

CarouselControl

Content distribution

Slots

Modal window

Refs

Header image

Feature lists

Scoped slots

Expandable text

Virtual DOM

Render functions

Vue Loader

Refactoring the main template as single-file component

Mounting the root-level component with a render function

Vue.js builds

Module system

Production builds

Full build vs runtime-only

Selecting a build

Summary

Building a Multi-Page App with Vue Router

Single-page applications

Routers

Vue Router

Special components

Vuebnb routing

Installing Vue Router

Creating routes

App component

Home page

Home route

Initial state

Refactoring

Home page initial state

Adding the thumbnail

Receiving in the client

ListingSummary component

In-app navigation

Adding a path to the model

Route navigation guards

next

HomePage component

Home API endpoint

Axios

Mixins

Moving the solution to a mixin

assignData

Linking to the listing page

Scroll behavior

Adding a footer

The route object

Dynamically selecting the container class

Listing summary image slider

Adding the slider

Translate

Carousel controls

Finishing touches

Summary

Managing Your Application State with Vuex

Flux application architecture

Principle #1 – Single source of truth

Principle #2 – Data is read-only

Principle #3 – Mutations are synchronous

Vuex

Installing Vuex

Save feature

ListingSave component

Saved state

Mutator method

Changing the icon to reflect the state

Adding to ListingPage

Making ListingSave a button

Moving page state into the store

State and mutator methods

Router

Retrieving page state from Vuex

Getters

Checking if page state is in the store

Saved page

Toolbar links

Summary

Adding a User Login and API Authentication with Passport

User model

Migration

Model

Seeder

Login system

LoginPage component

Server routes

CSRF protection

Post-login redirection

Adding authentication links to the toolbar

Protecting the saved route

Passing authentication state to the frontend

 auth meta property

Responding to authenticated state

Retrieving saved items from the database

Persisting saved listings

Creating an API route

Vuex actions

AJAX request

API authentication

OAuth

Laravel Passport

Attaching tokens

Summary

Deploying a Full-Stack App to the Cloud

Heroku

CLI

Creating an app

Source code

Environment variables

Creating a database

Default string length

Configuration

Configuring a web server

Passport keys

Deployment

Migration and seed

Serving static assets

Content distribution networks

KeyCDN

Uploading files with FTP

Environment variables

Skipping images

NPM scripts

Production build

Running the FTP script

Reading from the CDN

CDN helper

Setting the CDN URL

Using the CDN in Laravel

Using the CDN in Vue

Deploying to Heroku

Finale

Recap

Next steps

Summary

Preface

The year is 2014 and the war of Single-Page Application (SPA) solutions is truly raging. There are many rivals: Angular, React, Ember, Knockout, and Backbone, to name but a few. However, the battle being most closely watched is between Google's Angular and Facebook's React.

Angular, the SPA king until this point, is a full-fledged framework that follows the familiar MVC paradigm. React, the unlikely challenger seems quite odd in comparison with its core library only dealing with the view layer and markup written entirely in JavaScript! While Angular holds the bigger market share, React has caused a seismic shift in how developers think about web application design and has raised the bar on framework size and performance.

Meanwhile, a developer named Evan You was experimenting with his own new framework, Vue.js. It would combine the best features of Angular and React to achieve a perfect balance between simplicity and power. Your vision would resonate so well with other developers that Vue would soon be among the most popular SPA solutions.

Despite the fierce competition, Vue gained traction quickly. This was partly thanks to Taylor Otwell, the creator of Laravel, who tweeted in early 2015 about how impressed he was with Vue. This tweet generated a lot of interest in Vue from the Laravel community.

The partnership of Vue and Laravel would become further entwined with the release of Laravel version 5.3 in September 2016, when Vue was included as a default frontend library. This was a perfectly logical alliance for two software projects with the same philosophy: simplicity and an emphasis on the developer experience.

Today, Vue and Laravel offer an immensely powerful and flexible full-stack framework for developing web applications, and as you'll find throughout this book, they're a real treat to work with.

What this book covers

Building a full-stack app requires a wide variety of knowledge, not just about Vue and Laravel, but also Vue Router, Vuex, and Webpack, not to mention JavaScript, PHP, and web development in general.

As such, one of the biggest challenges for me as the author was deciding what should and shouldn't be included. The topics I ultimately settled upon arose as answers to one of the two following questions:

What are the essential features, tools, and design patterns that the reader will use in all, or most, of their Vue.js apps?

What are the key issues of designing and building

 

full-stack

 

Vue.js apps as opposed to other architectures?

Here's how the chosen topics are distributed across the chapters of the book:

Chapter 1, Hello Vue - An Introduction to Vue.js, presents an overview of Vue.js, and the book's case-study project, Vuebnb.

Chapter 2, Prototyping Vuebnb, Your First Vue.js Project, provides a practical introduction to the essential features of Vue.js, including installation, template syntax, directives, lifecycle hooks and so on.

Chapter 3, Setting Up a Laravel Development Environment, shows how to set up a new Laravel project for inclusion in a full-stack Vue.js app.

Chapter 4, Building a Web Service with Laravel, is about laying the foundations of the backend of our case-study project, by setting up the database, models, and API endpoints.

Chapter 5, Integrating Laravel and Vue.js with Webpack, explains how a sophisticated Vue app will require a build step, and introduces Webpack for bundling project assets.

Chapter 6, Composing Widgets with Vue.js Components, teaches how components are an essential concept of modern UI development and one of the most powerful features of Vue.js.

Chapter 7,Building a Multi-Page App with Vue Router, introduces Vue Router and shows how we can add virtual pages to a frontend app.

Chapter 8,Managing Your Application State with Vuex, explains how state management is a must-have feature for managing complex UI data. We introduce the Flux pattern and Vuex.

Chapter 9,Adding a User Login and API Authentication With Passport, focuses on one of the trickiest aspects of full-stack apps—authentication. This chapter shows how to use Passport for secure AJAX calls to the backend.

Chapter 10,Deploying a Full-Stack App to the Cloud, describes how to build and deploy our completed project to a cloud-based server and use a CDN for serving static assets.

What you need for this book

Before you begin development on the case-study project, you must ensure that you have the correct software and hardware.

Operating system

You can use a Windows or Linux-based operating system. I'm a Mac guy though, so any Terminal commands used in this book will be Linux commands.

Note that we'll be using the Homestead virtual development environment, which includes the Ubuntu Linux operating system. If you SSH into the box and run all your Terminal commands from there, you can use the same commands as me, even if you have a Windows host operating system.

Development tools

Downloading the project code will require Git. If you haven't got Git installed already, follow the directions in this guide: https://git-scm.com/book/en/v2/Getting-Started-Installing-Git.

To develop a JavaScript application you'll need Node.js and NPM. These can be installed from the same package; see the instructions here: https://nodejs.org/en/download/.

We'll also be using Laravel Homestead. Instructions will be given in Chapter 3, Setting Up a Laravel Development Environment.

Browser

Vue requires ECMAScript 5, which means you can use a recent version of any major browser to run it. I recommend you use Google Chrome, though, as I'll be giving debugging examples for Chrome Dev Tools, and it will be easier for you to follow along if you're using Chrome as well.

When choosing your browser, you should also consider compatibility with Vue Devtools.

Vue Devtools

The Vue Devtools browser extension makes debugging Vue a breeze, and we'll be using it extensively in this book. The extension is made for Google Chrome, but will also work in Firefox (and Safari, with a bit of hacking.)

See the following link for more information and installation instructions: https://github.com/vuejs/vue-devtools

IDE

You will, of course, need a text editor or IDE for developing the case-study project.

Hardware

You'll need a computer with specs sufficient for installing and running the software just mentioned. The most resource-intensive program will be VirtualBox 5.2 (or VMWare or Parallels), which we'll be using to set up the Homestead virtual development environment.

You'll also need an internet connection for downloading the source code and project dependencies.

Who this book is for

This book is for Laravel developers who are seeking a practical and best-practice approach to full-stack development with Vue.js and Laravel.

Any web developer interested in the topic can successfully use this book, though, so long as they meet the following criteria:

Topic

Level

HTML and CSS

Intermediate knowledge

JavaScript

Intermediate knowledge

PHP

Intermediate knowledge

Laravel

Basic knowledge

Git

Basic knowledge

Note that readers will not need any prior experience with Vue.js or other JavaScript frameworks.

Conventions

In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "For example, here I've created a custom element, grocery-item, which renders as a li."

A block of code is set as follows:

<

div

id

"

app

"

>

<!--Vue has dominion within this node-->

</

div

>

<

script

>

new

Vue

(

{

el

:

'#app'

}

)

;

</

script

>

Any command-line input or output is written as follows:

$ npm

install

New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "This is not permitted by Vue and if you attempt it you will get this error: Do not mount Vue to <html> or <body> - mount to normal elements instead."

Warnings or important notes appear in a box like this.
Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

You can download the code files by following these steps:

Log in or register to our website using your e-mail address and password.

Hover the mouse pointer on the

SUPPORT

tab at the top.

Click on

Code Downloads & Errata

.

Enter the name of the book in the

Search

box.

Select the book for which you're looking to download the code files.

Choose from the drop-down menu where you purchased this book from.

Click on

Code Download

.

You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

WinRAR / 7-Zip for Windows

Zipeg / iZip / UnRarX for Mac

7-Zip / PeaZip for Linux

The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Full-Stack-Vue.js-2-and-Laravel-5. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

Errata

Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

Piracy

Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at [email protected] with a link to the suspected pirated material.

We appreciate your help in protecting our authors and our ability to bring you valuable content.

Questions

If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.

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.

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

We will be exploring Webpack more extensively in Chapter 5, Integrating 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

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 4

,

 

Building 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 3

,

 

Setting Up a Laravel Development Environment

vuebnb-prototype

 

is the project code of the Vuebnb prototype that we'll build in

Chapter 2

,

 

Prototyping 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.

Prototyping Vuebnb, Your First Vue.js Project

In this chapter, we will learn the basic features of Vue.js. We'll then put this knowledge into practice by building a prototype of the case-study project, Vuebnb.

Topics this chapter covers:

Installation and basic configuration of Vue.js

Vue.js essential concepts, such as data binding, directives, watchers and lifecycle hooks

How Vue's reactivity system works

Project requirements for the case-study project

Using Vue.js to add page content including dynamic text, lists, and a header image

Building an image modal UI feature with Vue

Vuebnb prototype

In this chapter, we'll be building a prototype of Vuebnb, the case-study project that runs for the duration of this book. The prototype will just be of the listing page, and by the end of the chapter will look like this:

Figure 2.1. Vuebnb prototype

Once we've set up our backend in Chapter 3,