Vue.js 2.x by Example
eBook - ePub

Vue.js 2.x by Example

Mike Street, Bogdan-Alin Bâlc, Silva Pablo Henrique Penha

Compartir libro
  1. 412 páginas
  2. English
  3. ePUB (apto para móviles)
  4. Disponible en iOS y Android
eBook - ePub

Vue.js 2.x by Example

Mike Street, Bogdan-Alin Bâlc, Silva Pablo Henrique Penha

Detalles del libro
Vista previa del libro
Índice
Citas

Información del libro

Learn the fundamentals of vue.js by creating complex SPAs with Vuex, vue-router and moreAbout This Book• We bridge the gap between "learning" and "doing" by providing real-world examples that will improve your web development skills with Vue.js• Explore the exciting features of Vue.js 2 through practical and interesting examples• Explore modern development tools and learn how to utilize them by building applications with Vue.js Who This Book Is ForThis book is for developers who know the basics of JavaScript and are looking to learn Vue.js with real examples. You should understand the basics of JavaScript functions and variables and be comfortable with using CSS or a CSS framework for styling your projects.What You Will Learn• Looping through data with Vue.js• Searching and filtering data• Using components to display data• Getting a list of files using the dropbox API• Navigating through a file tree and loading folders from a URL• Caching with Vuex• Pre-caching for faster navigation• Introducing vue-router and loading components• Using vue-router dynamic routes to load data• Using vue-router and Vuex to create an ecommerce storeIn DetailVue.js is a frontend web framework which makes it easy to do just about anything, from displaying data up to creating full-blown web apps, and has become a leading tool for web developers. This book puts Vue.js into a real-world context, guiding you through example projects that helps you build Vue.js applications from scratch.With this book, you will learn how to use Vue.js by creating three Single Page web applications. Throughout this book, we will cover the usage of Vue, for building web interfaces, Vuex, an official Vue plugin which makes caching and storing data easier, and Vue-router, a plugin for creating routes and URLs for your application.Starting with a JSON dataset, the first part of the book covers Vue objects and how to utilize each one. This will be covered by exploring different ways of displaying data from a JSON dataset. We will then move on to manipulating the data with filters and search and creating dynamic values.Next, you will see how easy it is to integrate remote data into an application by learning how to use the Dropbox API to display your Dropbox contents in an applicationIn the final section, you will see how to build a product catalog and dynamic shopping cart using the Vue-router, giving you the building blocks of an e-commerce store.Style and approachThis book takes you three projects, with step-by-step instructions to help you understand the concepts of Vue and put it into practice.

Preguntas frecuentes

¿Cómo cancelo mi suscripción?
Simplemente, dirígete a la sección ajustes de la cuenta y haz clic en «Cancelar suscripción». Así de sencillo. Después de cancelar tu suscripción, esta permanecerá activa el tiempo restante que hayas pagado. Obtén más información aquí.
¿Cómo descargo los libros?
Por el momento, todos nuestros libros ePub adaptables a dispositivos móviles se pueden descargar a través de la aplicación. La mayor parte de nuestros PDF también se puede descargar y ya estamos trabajando para que el resto también sea descargable. Obtén más información aquí.
¿En qué se diferencian los planes de precios?
Ambos planes te permiten acceder por completo a la biblioteca y a todas las funciones de Perlego. Las únicas diferencias son el precio y el período de suscripción: con el plan anual ahorrarás en torno a un 30 % en comparación con 12 meses de un plan mensual.
¿Qué es Perlego?
Somos un servicio de suscripción de libros de texto en línea que te permite acceder a toda una biblioteca en línea por menos de lo que cuesta un libro al mes. Con más de un millón de libros sobre más de 1000 categorías, ¡tenemos todo lo que necesitas! Obtén más información aquí.
¿Perlego ofrece la función de texto a voz?
Busca el símbolo de lectura en voz alta en tu próximo libro para ver si puedes escucharlo. La herramienta de lectura en voz alta lee el texto en voz alta por ti, resaltando el texto a medida que se lee. Puedes pausarla, acelerarla y ralentizarla. Obtén más información aquí.
¿Es Vue.js 2.x by Example un PDF/ePUB en línea?
Sí, puedes acceder a Vue.js 2.x by Example de Mike Street, Bogdan-Alin Bâlc, Silva Pablo Henrique Penha en formato PDF o ePUB, así como a otros libros populares de Computer Science y Web Programming. Tenemos más de un millón de libros disponibles en nuestro catálogo para que explores.

Información

Año
2017
ISBN
9781788297479
Edición
1
Categoría
Web Programming

Building an E-Commerce Store – Browsing Products

In Chapter 9, Using Vue-Router Dynamic Routes to Load Data, we loaded our product data into the Vuex store and created a product detail page where a user could view the product and its variations. When viewing the product detail page, a user could change the variation from the drop-down and the price and other details would update.
In this chapter, we are going to:
  • Create a home page listing page with specific products
  • Create a category page with a reusable component
  • Create an ordering mechanism
  • Create filters dynamically and allow the user to filter the products

Listing the products

Before we create any filtering, curated lists, ordering components, and functionality, we need to create a basic product list – showing all the products first, and then we can create a paginated component that we can then reuse throughout the app.

Adding a new route

Let us add a new route to our routes array. For now, we'll work on the HomePage component, which will have the / route. Make sure you add it to the top of the routes array, so it doesn't get overridden by any of the other components:
const router = new VueRouter({
routes: [
{
path: '/',
name: 'Home',
component: HomePage
},
{
path: '/product/:slug',
component: ProductPage
},

{
path: '/404',
alias: '*',
component: PageNotFound
}
]
});
Within the HomePage component, create a new computed property and gather all the products from the store. Ensure the products have loaded before displaying anything in the template. Populate the HomePage component with the following code:
const HomePage = {
name: 'HomePage',

template: `<div v-if="products"></div>`,

computed: {
products() {
return this.$store.state.products;
}
}
};

Looping through products

When looking at a category listing for any shop, the data displayed tends to have a recurring theme. It normally consists of an image, title, price, and manufacturer.
Add an ordered list to your template – as the products are going to have an order to them, it makes semantic sense to place them in an ordered list. Within the <ol>, add a v-for looping through the products and displaying a title for each one, as shown here. It's also good practice to ensure the product variable exists before proceeding with displaying it:
template: `<div v-if="products">
<ol>
<li v-for="product in products" v-if="product">
<h3>{{ product.title }}</h3>
</li>
</ol>
</div>`,
When viewing the page in your browser, you may notice that the product list is very long. Loading images for every one of these products would be a huge load on the user's computer, along with overwhelming the user with that many products on display. Before we add more information, such as price and images, to our template, we'll look at paginating the products, allowing the data to be accessed in more manageable chunks.

Creating pagination

Creating pagination, initially, seems quite simple as you only need to return a fixed number of products. However, if we wish to make our pagination interactive and reactive to the product list it needs to be a bit more advanced. We need to build our pagination to be able to handle different lengths of products in the case where our product list has been filtered into fewer products.

Calculating the values

The arithmetic behind creating a pagination component and displaying the correct products relies on four main variables:
  • Items per page: This is usually set by the user; however, we'll use a fixed number of 12, to begin with
  • Total items: This is the total number of products to display
  • Number of pages: This can be calculated by dividing the number of products by the items per page
  • Current page number: This, combined with the others, will allow us to return exactly which products we need
From these numbers, we can calculate everything needed for our pagination. This includes what products to display, whether to show next/previous links and, if desired, a component to skip to different links.
Before we proceed, we are going to convert our products object into an array. This allows us to use the split method on it, which will allow us to return a specific list of products. It also means we can easily count the total number of items.
Update your products computed function to return an array instead of an object. This is done by using the map() function which is an ES2015 replacement for a simple for loop. This function now returns an array containing the product objects:
products() {
let products = this.$store.state.products;
return Object.keys(products).map(key => products[key]);
},
Create a new function in the computed object titled pagination. This function will return an object with various figures about our pagination, for example, the total number of pages. This will allow us to create a product list and update the navigation components. We need to only return the object if our products variable has data. The function is shown in the following code snippet:
computed: {
products() {
let products = this.$store.state.products;
return Object.keys(products).map(key => products[key]);
},

pagination() {
if(this.products) {

return {

}
}
}
},
We now need to keep track of two variables items perPage and the currentPage. Create a data function on your HomePage component and store these two variables. We'll give the user the ability to update the perPage variable later on. The highlighted code portion shows our data function:
const HomePage = {
name: 'HomePage',

template: `...`,

data() {
return {
perPage: 12,
currentPage: 1
}
},

computed: {
...
}
};
You may be wondering when to use local data on a component and when to store the information in the Vuex store. This all depends on where you are going to be using the data and what is going to manipulating it. As a general rule, if onl...

Índice