Reader small image

You're reading from  Frontend Development Projects with Vue.js 3 - Second Edition

Product typeBook
Published inMar 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781803234991
Edition2nd Edition
Languages
Tools
Right arrow
Authors (4):
Maya Shavin
Maya Shavin
author image
Maya Shavin

Maya is Senior Software Engineer in Microsoft, working extensively with JavaScript and frontend frameworks and based in Israel. She holds a B.Sc in Computer Sciences, B.A in Business Management, and an International MBA from University of Bar-Ilan, Israel. She has worked with JavaScript and latest frontend frameworks such as React, Vue.js, etc to create scalable and performant front-end solutions at companies such as Cooladata and Cloudinary, and currently Microsoft. She founded and is currently the organizer of the VueJS Israel Meetup Community, helping to create a strong playground for Vue.js lovers and like-minded developers. Maya is also a published author, international speaker and an open-source library maintainer of frontend and web projects.
Read more about Maya Shavin

Raymond Camden
Raymond Camden
author image
Raymond Camden

Raymond Camden is a developer advocate for IBM. His work focuses on the MobileFirst platform, Bluemix, hybrid mobile development, Node.js, HTML5, and web standards in general. He is a published author and presents at conferences and user groups on a variety of topics. Raymond can be reached at his blog, on Twitter, or via email. He is the author of many development books, including Apache Cordova in Action and Client-Side Data Storage.
Read more about Raymond Camden

Clifford Gurney
Clifford Gurney
author image
Clifford Gurney

Clifford Gurney is a solution-focused and results-oriented technical lead at a series-A funded startup. A background in communication design and broad exposure to leading digital transformation initiatives enriches his delivery of conceptually designed front-end solutions using Vue JS. Cliff has presented at the Vue JS Melbourne meetups and collaborates with other like-minded individuals to deliver best in class digital experience platforms.
Read more about Clifford Gurney

Hugo Di Francesco
Hugo Di Francesco
author image
Hugo Di Francesco

Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds a MEng degree in mathematical computation from University College London (UCL). He has used JavaScript across the stack to create scalable and performant platforms at companies such as Canon and Elsevier and in industries such as print on demand and mindfulness. He is currently tackling problems in the travel industry at Eurostar with Node.js, TypeScript, React, and Kubernetes while running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in the pursuit of which he trains and competes across the globe.
Read more about Hugo Di Francesco

View More author details
Right arrow

Understanding CSS modules

A recent pattern that has become popular in the reactive framework world is CSS modules. Frontend development always faces the issue of conflicting CSS class names, ill-structured BEM code, and confusing CSS file structures. Vue components help to solve this by being modular and allowing you to compose CSS that will generate unique class names for the specific component at compile time.

Using CSS modules in Vue exports CSS styles from the style section into JavaScript modules and uses those styles in the template and logic computing.

To enable this feature in Vue, you will need to add the module attribute to the style block, and reference as classes using the :class and $style.<class name> syntax, as shown here:

<template>
    <div :class="$style.container">CSS modules</div>
</template>
<style module>
.container {
  width: 100px;
  margin: 0 auto;
  background: green;
}
</style>

Once you have enabled the CSS module, the Vue engine exposes the $style object containing all the defined selectors as objects for use within the template section, and this.$style to use within the component’s JavaScript logic. In the preceding example, you are binding the CSS stylings defined for the.container class selector to div using $style.container.

If you inspected the DOM tree, that class would be called something such as .container_ABC123. If you were to create multiple components that had a semantic class name such as .container but used CSS modules, you would never run into style conflicts again.

Now, let’s practice using CSS modules to style a Vue component.

Exercise 1.12 – styling Vue components using CSS modules

To access the code file for this exercise, refer to https://github.com/PacktPublishing/Frontend-Development-Projects-with-Vue.js-3/tree/v2-edition/Chapter01/Exercise1.12.

Let’s start by performing the following steps:

  1. Use the application generated with npm init vue@3 as a starting point, or within the root folder of the code repository, navigate into the Chapter01/Exercise1.12 folder by using the following commands in order:
    > cd Chapter01/Exercise1.12/
    > yarn
  2. Run the application using the following command:
    yarn dev
  3. Open the exercise project in VS Code (by using the code . command within the project directory) or your preferred IDE.
  4. Create a new Vue component file named Exercise1-12.vue in the src/components directory.
  5. Inside Exercise1-12.vue, compose the following code:
    <template>
      <div>
        <h1>{{ title }}</h1>
        <h2>{{ subtitle }}</h2>
      </div>
    </template>
    <script>
    export default {
      data() {
        return {
          title: 'CSS module component!',
          subtitle: 'The fourth exercise',
        }
      },
    }
    </script>
  6. Add the <style> block and add module as an attribute instead of scoped:
    <style module>
    h1,
    h2 {
      font-family: 'Avenir', Helvetica, Arial, sans-serif;
      text-align: center;
    }
    .title {
      font-family: 'Avenir', Helvetica, Arial, sans-serif;
      color: #2c3e50;
      margin-top: 60px;
    }
    .subtitle {
      color: #4fc08d;
      font-style: italic;
    }
    </style>
  7. To use CSS modules in your template, you need to bind them to your HTML elements by using the :class syntax, which is the same as the v-bind:class directive:
    <h1 :class="$style.title">{{ title }}</h1>
    <h2 :class="$style.subtitle">{{ subtitle }}</h2>

When you save it, your project should look something like this:

Figure 1.48 – Output using CSS modules

Figure 1.48 – Output using CSS modules

  1. If you inspect the virtual DOM, you will see how it has applied unique class names to the bound elements:
Figure 1.49 – Generated CSS module class

Figure 1.49 – Generated CSS module class

In this exercise, we saw how to use CSS modules in your Vue components and how it works differently from CSS scoping.

In combination with file splitting and importing SCSS, using CSS modules is the preferred method for scoping component styling here. This safely ensures that individual component styles and business rules do not risk overriding each other and do not pollute global styling and variables with component-specific styling requirements.

Readability is important. The class name also hints at the component name as opposed to the v-data attribute, which can be good when debugging large projects.

In the next section, you will apply what you have learned in this chapter to build a dynamic shopping list app by combining directives, loops, two-way data, and method declaration for a Vue component together, with scoped CSS styling.

Activity 1.01 – building a dynamic shopping list app using Vue

To access the code file for this activity, refer to https://github.com/PacktPublishing/Frontend-Development-Projects-with-Vue.js-3/tree/v2-edition/Chapter01/Activity1.01

This activity aims to leverage your knowledge thus far about the basic features of an SFC, such as expressions, loops, two-way binding, and event handling.

This application should let users create and delete individual list items and clear the total list in one click.

The following steps will help you complete the activity:

  1. Build an interactive form in one component using an input bound to v-model.
  2. Add one input field to which you can add shopping list items. Allow users to add items by using the Enter key by binding a method to the @keyup.enter event.
  3. Users can expect to clear the list by deleting all the items or removing them one at a time. To facilitate this, you can use a delete method, which can pass the array position as an argument, or simply overwrite the whole shopping list data prop with an empty array, [].

The expected outcome is as follows:

Figure 1.50 – Expected output of Activity 1.01

Figure 1.50 – Expected output of Activity 1.01

Previous PageNext Page
You have been reading a chapter from
Frontend Development Projects with Vue.js 3 - Second Edition
Published in: Mar 2023Publisher: PacktISBN-13: 9781803234991
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Authors (4)

author image
Maya Shavin

Maya is Senior Software Engineer in Microsoft, working extensively with JavaScript and frontend frameworks and based in Israel. She holds a B.Sc in Computer Sciences, B.A in Business Management, and an International MBA from University of Bar-Ilan, Israel. She has worked with JavaScript and latest frontend frameworks such as React, Vue.js, etc to create scalable and performant front-end solutions at companies such as Cooladata and Cloudinary, and currently Microsoft. She founded and is currently the organizer of the VueJS Israel Meetup Community, helping to create a strong playground for Vue.js lovers and like-minded developers. Maya is also a published author, international speaker and an open-source library maintainer of frontend and web projects.
Read more about Maya Shavin

author image
Raymond Camden

Raymond Camden is a developer advocate for IBM. His work focuses on the MobileFirst platform, Bluemix, hybrid mobile development, Node.js, HTML5, and web standards in general. He is a published author and presents at conferences and user groups on a variety of topics. Raymond can be reached at his blog, on Twitter, or via email. He is the author of many development books, including Apache Cordova in Action and Client-Side Data Storage.
Read more about Raymond Camden

author image
Clifford Gurney

Clifford Gurney is a solution-focused and results-oriented technical lead at a series-A funded startup. A background in communication design and broad exposure to leading digital transformation initiatives enriches his delivery of conceptually designed front-end solutions using Vue JS. Cliff has presented at the Vue JS Melbourne meetups and collaborates with other like-minded individuals to deliver best in class digital experience platforms.
Read more about Clifford Gurney

author image
Hugo Di Francesco

Hugo Di Francesco is a software engineer who has worked extensively with JavaScript. He holds a MEng degree in mathematical computation from University College London (UCL). He has used JavaScript across the stack to create scalable and performant platforms at companies such as Canon and Elsevier and in industries such as print on demand and mindfulness. He is currently tackling problems in the travel industry at Eurostar with Node.js, TypeScript, React, and Kubernetes while running the eponymous Code with Hugo website. Outside of work, he is an international fencer, in the pursuit of which he trains and competes across the globe.
Read more about Hugo Di Francesco