Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Frontend Development Projects with Vue.js 3
Frontend Development Projects with Vue.js 3

Frontend Development Projects with Vue.js 3: Learn the fundamentals of building scalable web applications and dynamic user interfaces with Vue.js , Second Edition

Arrow left icon
Profile Icon Maya Shavin Profile Icon Clifford Gurney Profile Icon Raymond Camden Profile Icon Hugo Di Francesco
Arrow right icon
€37.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4 (15 Ratings)
Paperback Mar 2023 628 pages 2nd Edition
eBook
€20.98 €29.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m
Arrow left icon
Profile Icon Maya Shavin Profile Icon Clifford Gurney Profile Icon Raymond Camden Profile Icon Hugo Di Francesco
Arrow right icon
€37.99
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4 (15 Ratings)
Paperback Mar 2023 628 pages 2nd Edition
eBook
€20.98 €29.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m
eBook
€20.98 €29.99
Paperback
€37.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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 feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Frontend Development Projects with Vue.js 3

Starting Your First Vue Project

In this chapter, you will learn about the key concepts and benefits of Vue.js (Vue), how to set up the project architecture using the terminal (or command line), and how to create a simple Vue component with local data following the component fundamentals.

This chapter will cover the following topics:

  • Understanding Vue as a framework
  • Setting up a Vite-powered Vue application
  • Exploring data properties as a local state
  • Writing components with <script setup>
  • Understanding Vue directives
  • Enabling two-way binding using v-model
  • Understanding data iteration with v-for
  • Exploring methods
  • Understanding component lifecycle hooks
  • Styling components
  • Understanding CSS modules

By the end of this chapter, you will be able to describe the fundamentals of Vue lifecycle hooks and expressions and use various styling approaches and HTML syntax flavors to control the HTML template competently.

Technical requirements

The Node version has to be below v20 (preferable Yarn 1.22 and Node version above 16 and up to 19.x, and npm up to version 9.x.

The complete code for this chapter is available on GitHub at: https://github.com/PacktPublishing/Frontend-Development-Projects-with-Vue.js-3/tree/v2-edition/Chapter01

Understanding Vue as a framework

Developers in the industry must resolve frontend development problems quickly with minimal impact on existing workflows or backend architecture. In many cases, developers tend to overlook the UI until the end of a project, which can happen because of a lack of resources, ever-evolving product requirements, or the existing attitude that the frontend is the easy bit.

However, companies such as Apple and Google have proven that thinking through the design of the frontend is key to a solid product or platform that will excite and engage users, leading to a higher return on investment and a more successful business.

If you know Vue, you may have also come across other frontend frameworks that, at face value, solve the same problems, such as Ember, Angular, or React. At a surface level, they attempt to make reactive frontend development more reliable and introduce patterns that make it easier. However, there are significant differences in how a Vue project might play out compared to an Angular or React project. Let’s investigate them.

Angular versus Vue

Angular is a Model-View-ViewModel (MVVM) framework built by Google and has built-in support for TypeScript. The Angular ecosystem includes Ahead-of-Time (AoT) rendering, a router, and a CLI tool. However, it fails to deliver a simplified system for global state management; developers would need to learn how to use Flux or adopt NgRx.

Vue takes Angular’s core robustness and provides a better development experience by removing the restriction of an enforced code style for developers. Vue also simplifies common Angular patterns, such as HTML directives, and eliminates a variety of Angular’s project structures, such as injectables, components, pipes, modules, and so on. From Vue 3.0 onward, it provides excellent support for TypeScript and typing without the drawbacks of Angular-enforced coding styles.

Vue is more flexible, developer-friendly, efficient, and straightforward to set up and learn to use than Angular in many cases.

Next, let’s look at how Vue and React differ.

React versus Vue

First released in 2013 and backed by Meta (previously known as Facebook), React rapidly gained popularity in the developer community. React introduces the JSX pattern to write HTML syntax directly with JavaScript. With JSX, React increases the amount that new developers are required to learn about both JavaScript and component-based architecture.

Both React and Vue share the same component-driven development approach, allowing developers to build applications in a modular way. Each component contains its functionalities and lifecycle. Vue takes these core concepts of modular coding and offers flexibility to developers in choosing which approach to use to write their components: JSX or the traditional style, in which HTML, CSS, and JavaScript are separated.

Vue uses the Single-File Component (SFC) approach to leverage this modular structure into a single file while keeping the separation readable and understandable for developers.

Advantages of using Vue for your project

Vue has a gentler learning curve and a vibrant ecosystem. This gentle learning curve helps reduce overhead and cost for any team onboarding developers to a new Vue project.

One key benefit of Vue is its approachability for both new and veteran developers:

  • Out of the box, developers can use a well-optimized and performant framework on which to build scalable, dynamic frontend applications.
  • The SFC format pattern offers a modular and flexible blueprint that provides an enjoyable experience to developers. SFCs allow Vue to be genuinely versatile. You can implement basic functionalities and incrementally adopt pieces of a static site into Vue rather than overhaul your entire website.

As powerful as Redux and NgRx, Vuex (and lately Pinia) proves to be an outstanding official global state management tool that is flexible enough to meet most development needs.

Thanks to its stable performance; well-defined tools such as Vue Router, Pinia, Vuex, and so on; and a supportive community, developers can save time and money by choosing Vue for their development stack.

The following section explores the essential Vue architecture before deep-diving into the SFC pattern and template syntax.

Working with Vue

To learn about the Vue architecture, we will start by importing the Vue package into our coding playground. One straightforward way is to import the Vue package through the official Content Distribution Network (CDN). We can do so by creating an index.html file and adding a <script> tag to load the Vue CDN within the <head> section of the HTML template, as demonstrated in the following code block:

<!DOCTYPE html>
<html>
<head>
    <title>Vue.js project with CDN</title>
    <script src="https://unpkg.com/vue@3"></script>
</head>
</html>

The browser will also load the Vue package using the CDN defined in the script tag when loading the page. Once completed, you can utilize the Vue functions and start writing Vue code.

But first, let’s look at the Vue instance.

Understanding the Vue instance

In general, each Vue application consists of only one root Vue instance, which can be created using the Vue.createApp method:

const vm = Vue.createApp({
  // options
})

The Vue class constructor accepts an options object for the configurations and behavior of components. We call this approach Options API and we can use it for all corresponding Vue components. However, all of them are considered nested Vue instances, with their own options and properties.

Note

vm is a term commonly used to refer to a View Model, which is an abstraction of the view that describes the state of the data in the model. Binding a Vue instance to vm helps you to keep track of your Vue instance in a block of code.

For the Vue engine to render the application instance, in our index.html file, we declare an <div> element within the <body> tag using a unique class name, ID, or data attribute as the main entry point for the application accordingly:

<body>
  <div id="vue-app"></div>
  <script>
    const vm = Vue.createApp({
    //Options
    })
  </script>
</body>

To render the Vue application in the browser, we need to trigger vm.mount() to mount the root component to the targeted HTML element using a unique selector. In this example, it is an id with a value of vue-app:

<body>
  <div id="vue-app"></div>
  <script>
    const vm = Vue.createApp({
               //Options
               })
    vm.mount('#vue-app')
  </script>
</body>

Now, you bind the <div> element with id="vue-app" to the new Vue instance.

Next, let’s define text with a value of "Start using Vue.js today!" and add it as a property of the return value for the data method in the application options:

const vm = Vue.createApp({
  data() {
   return {
    text: 'Start using Vue.js today!'
   }
  }
})

In the preceding code example, data is a function that returns an Object instance containing the local state (or local variables) of a component. We will discuss this further in an upcoming section of this chapter.

To render the content of text to the DOM, we use Vue template syntax, represented by double curly braces ({{}}) wrapped around the reactive content. In this case, we use {{ text }}, as shown in the following code:

<div id="vue-app">{{ text }}</div>

The Vue engine will replace the data property labeled text and the curly brace placeholder with the Start using Vue.js today! string.

The output of the preceding code will be as follows:

Figure 1.1 – Displaying “Start using Vue.js today!” using a local data property

Figure 1.1 – Displaying “Start using Vue.js today!” using a local data property

In the <head> tag, we can also use the DOM API to construct a Vue application instance and bound it to our target element (with the ID selector as #vue-app):

<head>
  <title>Vue.js CDN</title>
  <script src="https://unpkg.com/vue@3"></script>
  <script>
    document.addEventListener('DOMContentLoaded', function
    () {
     Vue.createApp({
       data(){
         return {
           text: "Start using Vue.js today!"
         }
       }
      }).mount('#vue-app')
     })
  </script>
</head>
<body>
 <div id="vue-app">{{text}}</div>
</body>

The output is the same for both approaches. However, we strongly recommend not using DOMContentLoaded.

While working with a CDN is very portable, we recommend using package managers as the installation method for Vue. From Vue 3 and above, Vue projects use Vite (or Vite.js) to initialize and bundle the code. You can access it here: https://vuejs.org/guide/quick-start.html#creating-a-vue-application.

Using a bundling management tool is very helpful for managing other third-party libraries and building an optimized code package for production. In the next section, we will explore a package-controlled example.

Setting up a Vite-powered Vue application

A Vue project is structured similarly to a lot of modern node-based apps and contains the following:

  • A package.json file
  • A node_modules folder in the root of your project
  • Various other configuration files are usually contained at the root level, such as vite.config.js and .eslintrc.js, since they will generally have an effect across your whole project.

The following screenshot displays a default Vue app folder structure:

Figure 1.2 – Default Vue application folder structure

Figure 1.2 – Default Vue application folder structure

By default, there is an index.html file at the root level that serves as a placeholder for loading the Vue application. You can modify this file to include header and footer scripts, such as Google Fonts or third-party JavaScript libraries that are not included as a part of your bundle.

The Vue project structure follows a pattern where you manage most of your source code within the /src directory. You can subdivide your Vue files into various folders, for example, using a components folder to store reusable Vue components. By default, Vite will create assets and components folders to code-split the default files. For beginners, it is good to follow this pattern until you get more comfortable:

Figure 1.3 – Default Vue application src folder structure

Figure 1.3 – Default Vue application src folder structure

The public folder is a special directory containing files that need to be transferred directly to the output location. The following screenshot displays how this folder will look:

Figure 1.4 – Default Vue application public folder

Figure 1.4 – Default Vue application public folder

At this point, you should be somewhat familiar with how a Vue project structure looks. Next, we discuss Vue’s unique pattern – the SFC architecture.

Vue’s SFC architecture

Components are the building blocks of most modern frameworks. In general, splitting your code into component-specific chunks ensures code readability and facilitates the Don’t Repeat Yourself (DRY) principle. Vue’s SFC pattern follows this approach closely.

The SFC architecture centralizes the responsibility of both appearance and behavior into a single file, thus simplifying the architecture of your project. You now can refer to your HTML, CSS, and JavaScript logic without switching files. Your default .vue file structure will be as follows:

Figure 1.5 – Default .vue file structure

Figure 1.5 – Default .vue file structure

A general good practice is to ensure your components file doesn’t contain more than 500 lines of code. If you encounter this situation, it’s recommended to split them into smaller reusable components. For example, in the header of your application, you may have a logo element that is reused on other pages. You would create a component such as logo.vue:

// logo.vue
<template>
  <img src="myLogo.png" />
</template>

In header.vue, you import the logo component into the script section and then include it as a nested component of the header component. You can achieve this by declaring it as a property of the components field:

// header.vue
<script>
    import logo from 'components/logo.vue'
    export default {
        components: {
          logo
        }
    }
</script>

In the template section, you can use the logo as a normal HTML element, as shown here:

<template>
    <header>
      <a href="mywebsite.com">
        <logo />
      </a>
    </header>
</template>

The output will be a header with the logo image rendered – and you can reuse the logo component in any other component when needed.

Very soon, you will have lots of these semantically structured files, which use small chunks of a reusable syntax that your team can implement across various application areas.

In the next exercise, you will practice creating your first Vue component and displaying it in another component.

Exercise 1.01 – building your first component

We are going to build our first component, Exercise1.01, inside of a Vue project and import it to use it in the App.vue component using ES6 module syntax.

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

Note

Your app will hot-reload when you save new changes, so you can see them instantly.

To get started, execute 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.01 folder by using the following commands in order:
    > cd Chapter01/Exercise1.01/
    > yarn
  2. Run the application using the following command:
    yarn dev
  3. Go to https://localhost:3000.
  4. Open the exercise project in VS Code (by using the code . command within the project directory) or your preferred IDE.
  5. Open the src/App.vue file, delete everything in that file, and save.
  6. In your browser, everything should be a blank, clean state to start working from.
  7. The three primary components that make up a single-file component are the <template>, <script>, and <style> blocks. Add the following code blocks as our scaffolding for a Vue component:
    /** src/App.vue **/
    <template>
    </template>
    <script>
    export default {
    }
    </script>
    <style>
    </style>
  8. Create another file in the components folder called Exercise1-01.vue and repeat the same step for scaffolding the Vue component:
    // src/components/Exercise1-01.vue
    <template>
    </template>
    <script>
    export default {
    }
    </script>
    <style>
    </style>
  9. Within our Exercise1-01.vue component, compose a set of <div> tags, with an <h1> element and a heading inside the <template> tags:
    <template>
      <div>
        <h1>My first component!</h1>
      </div>
    </template>
  10. Inside the <style> block, add some styling as follows:
    <style>
      h1 {
        font-family: 'Avenir', Helvetica, Arial,
        sans-serif;
        text-align: center;
        color: #2c3e50;
        margin-top: 60px;
      }
    </style>
  11. Import our component into App.vue by using the ES6 import method and defining the component inside the components object in the <script> block. We can now reference this component inside the HTML by using its name in camelCase or kebab-case (both will work):
    <template>
      <Exercise />
    </template>
    <script>
    import Exercise from './components/Exercise1-01'
    export default {
      components: {
        Exercise,
      }
    }
    </script>

When you press Ctrl + S (or Cmd + S on macOS), https://localhost:3000 should reload and look amazing:

Figure 1.6 – localhost output for Exercise 1.01

Figure 1.6 – localhost output for Exercise 1.01

In this exercise, we saw how to structure Vue components using template tags, and scaffold basic Vue components using Vetur. We also created a new Vue component and reuse it in App.vue using ES6 syntax and property field components.

In the next section, we will gain an understanding of how to define the local state data of a component using data properties.

Exploring data properties as a local state

One of the most used terms and reactive elements used when constructing Vue components is data properties. These manifest themselves within the data() function of a Vue instance:

<script>
    export default {
        data() {
          return {
            color: 'red'
          }
        }
    }
</script>

You can use the data() function to create a local data object to essentially store any information you want to use within your Vue templates. This local object is bound to the component and we call it the local state data of the component. When any property of this local object is updated or changed, it will reactively update in the corresponding template.

Once we have defined our local data, we need to bind it to the template section to display its values in the UI, which is called data interpolation.

Interpolation is the insertion of something of a different nature into something else. In the Vue context, this is where you would use mustache syntax (double curly braces) to define an area in which you can inject data into a component’s HTML template.

Consider the following example:

<template>
  <span> {{ color }}</span>
</template >
<script>
export default {
  data() {
    return {
      color: 'red'
    }
  }
}
</script>

The data property of red is bound to Vue.js reactive data and will update during runtime, depending on state changes between the UI and its data.

At this point, we should look at how to define and bind local data in the most classical Vue way. With Vue 3.0, we enjoy a shorter and simpler approach to writing and importing components. Let’s explore it next.

Writing components with script setup

Starting from Vue 3.0, Vue introduces a new syntactic sugar setup attribute for the <script> tag. This attribute allows you to write code using Composition API (which we will discuss further in Chapter 5, The Composition API) in SFCs and shorten the amount of code needed for writing simple components.

The code block residing within the <script setup> tag will then be compiled into a render() function before being deployed to the browser, providing better runtime performance.

To start using this syntax, we take the following example code:

// header.vue
<script>
    import logo from 'components/logo.vue'
    export default {
        components: {
          logo
        }
    }
</script>

Then, we replace <script> with <script setup>, and remove all the code blocks of export default…. The example code now becomes as follows:

// header.vue
<script setup>
    import logo from 'components/logo.vue'
</script>

In <template>, we use logo as usual:

<template>
    <header>
      <a href="mywebsite.com">
        <logo />
      </a>
    </header>
</template>

To define and use local data, instead of using data(), we can declare regular variables as local data and functions as local methods for that component directly. For example, to declare and render a local data property of color, we use the following code:

<script setup>
const color = 'red';
</script>
<template>
  <div>{{color}}</div>
</template>

The preceding code outputs the same result as the example in the previous section –red.

As mentioned at the beginning of this section, <script setup> is the most useful when you need to use Composition API within SFCs. Still, we can always take advantage of its simplicity for simple components.

Note

From this point onward, we will combine both approaches and use <script setup> whenever possible.

In the following exercise, we will go into more detail about how to use interpolation and data.

Exercise 1.02 – interpolation with conditionals

When you want to output data into your template or make elements on a page reactive, interpolate data into the template by using curly braces. Vue can understand and replace that placeholder with data.

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.02:

  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.02 folder by using the following commands in order:
    > cd Chapter01/Exercise1.02/
    > 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-02.vue in the src/components directory.
  5. Inside the Exercise1-02.vue component, let’s add data within the <script setup> tags by adding a function called data(), and return a key called title with your heading string as the value:
    <script>
    export default {
      data() {
        return {
          title: 'My first component!',
        }
      },
    }
    </script>
  6. Reference title by replacing your <h1> text with the interpolated value of {{ title }}:
    <template>
      <div>
        <h1>{{ title }}</h1>
      </div>
    </template>

When you save this document, the data title will now appear inside your h1 tag.

  1. In Vue, interpolation will resolve any JavaScript that’s inside curly braces. For example, you can transform the text inside your curly braces using the toUpperCase() method:
    <template>
      <div>
        <h1>{{ title.toUpperCase() }}</h1>
      </div>
    </template>
  2. Go to https://localhost:3000. You should see an output like the following screenshot:
Figure 1.7 – Display of an uppercase title

Figure 1.7 – Display of an uppercase title

  1. Interpolation can also handle conditional logic. Inside the data object, add a Boolean key-value pair, isUppercase: false:
    <template>
      <div>
        <h1>{{ isUppercase ? title.toUpperCase() : title }}</h1>
      </div>
    </template>
    <script>
    export default {
      data() {
        return {
          title: 'My first component!',
          isUppercase: false,
        }
      },
    }
    </script>

The preceding code will generate the following output:

Figure 1.8 – Exercise 1.02 output after including the inline conditional statement

Figure 1.8 – Exercise 1.02 output after including the inline conditional statement

  1. Add this condition to the curly braces and when you save, you should see the title in sentence case. Play around with this value by changing isUppercase to true:
    <script>
    export default {
      data() {
        return {
          title: 'My first component!',
          isUppercase: true,
        }
      },
    }
    </script>

The following screenshot displays the final output generated upon running the preceding code:

Figure 1.9 – Displaying the uppercase title

Figure 1.9 – Displaying the uppercase title

  1. Now, let’s replace <script> with <script setup> and move all the local data declared within the data() function to its own variable names respectively, such as title and isUpperCase, as shown here:
    <script setup>
    const title ='My first component!';
    const isUppercase = true;
    </script>
  2. The output should remain the same as in Figure 1.9.

In this exercise, we were able to apply inline conditions within the interpolated tags ({{}}) by using a Boolean variable. The feature allows us to modify what data to display without overly complicated situations, which can be helpful in certain use cases. We also learned how to write a more concise version of the component using <script setup> in the end.

Since we are now familiar with using interpolation to bind local data, we will move on to our next topic – how to attach data and methods to HTML element events and attributes using Vue attributes.

Understanding Vue directives

All Vue-based directives start with a v-* prefix as a Vue-specific attribute:

  • v-text: The v-text directive has the same reactivity as with interpolation. Interpolation with {{ }} is more performant than the v-text directive. However, you may find yourself in situations where you have pre-rendered text from a server and want to override it once your Vue application has finished loading. For example, you can pre-define a static placeholder text while waiting for the Vue engine to eventually replace it with the dynamic value received from v-text, as shown in the following code block:
    <template>
      <div v-text="msg">My placeholder</div>
    </template>
    <script setup>
    const msg = "My message"
    </script>
  • v-once: When used, it indicates the starting point of static content. The Vue engine will render the component with this attribute and its children exactly once. It also ignores all data updates for this component or element after the initial render. This attribute is handy for scenarios with no reactivity needed for certain parts. You can combine v-once with v-text, interpolation, and any Vue directive.
  • V-html: Vue will parse the value passed to this directive and render your text data as a valid HTML code into the target element. We don’t recommend using this directive, especially on the client side, due to its performance impact and the potential security leak. The script tag can be embedded and triggered using this directive.
  • v-bind: This directive is one of the most popular Vue features. You can use this directive to enable one-way binding for a data variable or an expression to an HTML attribute, as shown in the following example:
    <template>
      <img v-bind:src="logo" />
    </template>
    <script setup>
    const logo = '../assets/logo.png';
    </script>

The preceding code demonstrates how to bind the logo data variable to image’s src. The img component now takes the source value from the logo variable and renders the image accordingly.

You can also use it to pass a local data variable as props to another component. A shorter way is using the :attr syntax instead of v-bind:attr. Take the preceding example, for instance. We can rewrite the template as follows:

<template>
  <img :src="logo" />
</template>
  • v-if: This is a powerful directive you can use to conditionally control how elements render inside a component. This directive operates like the if…else and if…else if… conditions. It comes with supporting directives, such as v-else, standing for the else case, and v-else-if, standing for the else if case. For example, we want to render different text when count is 2, 4, and 6. The following code will demonstrate how to do so:
    <template>
    <div v-if="count === 2">Two</div>
    <div v-else-if="count === 4">Four</div>
    <div v-else-if="count === 6">Six</div>
    <div v-else>Others</div>
    </template>
  • v-show: You can also control the visible state of HTML elements by using v-show. Unlike v-if, with v-show, the Vue engine still mounts the element to the DOM tree but hides it using the display: none CSS style. You can still see the content of the hidden element visible in the DOM tree upon inspecting it, but it is not visible on the UI to end users. This directive does not work with v-else or v-else-if. If v-show results in a true Boolean, it will leave the DOM element as is. If it resolves as false, it will apply the display: none style to the element.
  • v-for: We use the v-for directive to accomplish the goal of list rendering based on a data source. The data source is an iterative data collection, such as an array or object. We will dive deeper into different use cases for this directive in a separate section within this chapter.

We have gone over the most common directives in Vue. Let’s review and experiment with how to use these directives with the following exercise.

Exercise 1.03 – exploring basic directives (v-text, v-once, v-html, v-bind, v-if, v-show)

More complicated components will use multiple directives to achieve the desired outcome. In this exercise, we will construct a component that uses several directives to bind, manipulate, and output data to a template view.

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

Let’s start the exercise 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.03 folder by using the following commands in order:
    > cd Chapter01/Exercise1.03/
    > yarn
  2. Run the application using the following command:
    yarn dev
  3. Open the exercise project in VS Code (by using code . command within the project directory) or your preferred IDE.
  4. Create a new Vue component file named Exercise1-03.vue in the src/components directory.
  5. Inside Exercise1-03.vue, compose the following code to display the text content:
    <template>
      <div>
        <h1>{{ text }}</h1>
      </div>
    </template>
    <script setup>
    const text = 'Directive text';
    </script>
  6. Replace the {{}} interpolation with the v-text attribute. The output should not change:
    <template>
      <div>
        <h1 v-text="text">Loading...</h1>
      </div>
    </template>

Figure 1.10 displays the output of the preceding code:

Figure 1.10 – Same output for v-text and the interpolation method

Figure 1.10 – Same output for v-text and the interpolation method

  1. Add the v-once directive to the same element. This will force this DOM element to only load the v-text data once:
    <template>
      <div>
        <h1 v-once v-text="text">Loading...</h1>
      </div>
    </template>
  2. Underneath the h1 element, include a new h2 element that uses the v-html attribute. Add a new local data called html that contains a string with HTML formatting in it, as shown in the following code block:
    <template>
      <div>
        <h1 v-once v-text="text">Loading...</h1>
        <h2 v-html="html" />
      </div>
    </template>
    <script setup>
    const text = 'Directive text';
    const html = 'Stylise</br>HTML in<br/><b>your data</b>'
    </script>

Running the preceding code will generate an output as follows:

Figure 1.11 – Rendering HTML elements from a string using v-html

Figure 1.11 – Rendering HTML elements from a string using v-html

  1. Add a new local link object that contains a bunch of information such as the URL, target, title, and tab index. Inside the template, add a new anchor HTML element and bind the link object to the HTML element using the v-bind short syntax – for example, :href="link.url":
    <template>
      <div>
        <h1 v-once v-text="text">Loading...</h1>
        <h2 v-html="html" />
        <a
          :href="link.url"
          :target="link.target"
          :tabindex="link.tabindex"
          >{{ link.title }}</a>
      </div>
    </template>
    <script setup>
    const text = 'Directive text';
    const html = 'Stylise</br>HTML in<br/><b>your data</b>'
    const link = {
      title: "Go to Google",
      url: https://google.com,
      tabindex: 1,
      target: '_blank',
    };
    </script>

The following screenshot displays the output:

Figure 1.12 – Output on binding the reactive data from the Vue instance to any HTML attribute

Figure 1.12 – Output on binding the reactive data from the Vue instance to any HTML attribute

  1. Apply v-if="false" to the h1 element, v-else-if="false" to h2, and v-else to the a tag like this:
    <template>
      <div>
        <h1 v-if="false" v-once v-text="text">Loading...
        </h1>
        <h2 v-html="html" v-else-if="false" />
        <a
          v-else
          :href="link.url"
          :target="link.target"
          :tabindex="link.tabindex"
          >{{ link.title }}</a>
      </div>
    </template>

You should only see the <a> tag on the page since we have set the main conditional statements to false.

The v-else condition will display the following:

Figure 1.13 – false v-if statements hiding the whole HTML element from the DOM

Figure 1.13 – false v-if statements hiding the whole HTML element from the DOM

  1. Change the template to use v-show instead of the v-if statements, remove v-else from the <a> element, and change the value of v-show in h1 to true:
    <template>
      <div>
        <h1 v-show="true" v-once v-text="text">Loading...
        </h1>
        <h2 v-html="html" v-show="false" />
        <a
          :href="link.url"
          :target="link.target"
          :tabindex="link.tabindex"
          >{{ link.title }}</a>
      </div>
    </template>

The output of the preceding code will be as follows:

Figure 1.14 – Changing v-show to true will display the main directive text

Figure 1.14 – Changing v-show to true will display the main directive text

When you open the Elements tab of your browser Devtools, you should be able to observe that the h2 display state is set to none as follows:

Figure 1.15 – h2 has “display: none” for the false condition

Figure 1.15 – h2 has “display: none” for the false condition

In this exercise, we learned about the core Vue directives to control, bind, show, and hide HTML template elements without requiring any JavaScript outside of adding new data objects to your local state.

In the next section, we will learn how to achieve two-way binding with the help of Vue’s v-model.

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Work through mini projects, exercises, and activities to learn Vue.js in a practical way
  • Create dynamic components and user interfaces that are fast and intuitive
  • Find out how you can get the most out of the Vue.js 3 framework and build an end-to-end project

Description

Are you looking to use Vue.js 3 for building web apps but don't know where to begin? Frontend Development Projects with Vue.js 3 will help you get to grips with the core concepts of this JavaScript framework using practical examples that simulate real-world web projects. With this updated edition, you’ll experience all aspects of the new and improved Vue.js 3 as you work on mini projects such as a chat interface, a shopping cart, a price calculator, a to-do app, and a profile card generator for storing contact details. These realistic projects are presented as bite-size exercises that you can enjoy even as you challenge yourself. Throughout the book, you'll discover how to manage data in Vue components, define communication interfaces between components, and handle static and dynamic routing to control application flow. You'll also work with Vite and Vue DevTools and learn how to handle transition and animation effects for an engaging user experience. Finally, you’ll see how to test your app and deploy it to the web. By the end of this Vue.js book, you'll have the skills that enable you to work like an experienced Vue developer to build professional apps that can be used by others and have the confidence to tackle real-world frontend web development problems.

Who is this book for?

This book is designed for Vue.js beginners. Whether this is your first JavaScript framework, or if you're already familiar with React or Angular, this book will get you on the right track. To understand the concepts explained in this book, you must be familiar with HTML, CSS, JavaScript, and Node package management.

What you will learn

  • Set up a development environment and start your first Vue.js 3 project
  • Modularize a Vue application using component hierarchies
  • Use external JavaScript libraries to create animations
  • Share state between components and use Pinia for state management
  • Work with APIs using Pinia and Axios to fetch remote data
  • Validate functionality with unit testing and end-to-end testing
  • Get to grips with web app deployment
Estimated delivery fee Deliver to Luxembourg

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Mar 17, 2023
Length: 628 pages
Edition : 2nd
Language : English
ISBN-13 : 9781803234991
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
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 feature icon AI Assistant (beta) to help accelerate your learning
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Luxembourg

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Mar 17, 2023
Length: 628 pages
Edition : 2nd
Language : English
ISBN-13 : 9781803234991
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.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
€189.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
€264.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 97.97
Vue.js 3 Design Patterns and Best Practices
€29.99
Frontend Development Projects with Vue.js 3
€37.99
Architecting Vue.js 3 Enterprise-Ready Web Applications
€29.99
Total 97.97 Stars icon

Table of Contents

19 Chapters
Part 1: Introduction and Crash Course Chevron down icon Chevron up icon
Chapter 1: Starting Your First Vue Project Chevron down icon Chevron up icon
Chapter 2: Working with Data Chevron down icon Chevron up icon
Chapter 3: Vite and Vue Devtools Chevron down icon Chevron up icon
Part 2: Building Your First Vue App Chevron down icon Chevron up icon
Chapter 4: Nesting Components (Modularity) Chevron down icon Chevron up icon
Chapter 5: The Composition API Chevron down icon Chevron up icon
Chapter 6: Global Component Composition Chevron down icon Chevron up icon
Chapter 7: Routing Chevron down icon Chevron up icon
Chapter 8: Animations and Transitions Chevron down icon Chevron up icon
Part 3: Global State Management Chevron down icon Chevron up icon
Chapter 9: The State of Vue State Management Chevron down icon Chevron up icon
Chapter 10: State Management with Pinia Chevron down icon Chevron up icon
Part 4: Testing and Application Deployment Chevron down icon Chevron up icon
Chapter 11: Unit Testing Chevron down icon Chevron up icon
Chapter 12: End-to-End Testing Chevron down icon Chevron up icon
Chapter 13: Deploying Your Code to the Web Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon
Other Books You May Enjoy Chevron down icon Chevron up icon

Customer reviews

Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.4
(15 Ratings)
5 star 66.7%
4 star 13.3%
3 star 13.3%
2 star 6.7%
1 star 0%
Filter icon Filter
Top Reviews

Filter reviews by




Nicolas Alexander Rau Nov 04, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I recommend this ebook because It´s a quite good reference for the Vue JS Framework.
Feefo Verified review Feefo
Patsy Phelan Jan 19, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Feefo Verified review Feefo
Milos Pavlovic Aug 01, 2024
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Feefo Verified review Feefo
Nina Ortega Mar 24, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I received this book for free from a connection through LinkedIn and I was eager to read through it since I use Vue.js a lot in my work and personal projects.I found this book to be an amazing resource. The two specific things I loved were the design of the book, the colors, sizes, and fonts used added so much to the read and made it a lot easier to follow than other books that I have read.The instructions in the book were also clear and easy to follow which is something that I really appreciated. Instead of digging through the same font text to find a line of code all the code is written out in different color text blocks in a different font.I definitely recommend this book to people like me, who struggle reading jargon-heavy documentation and just want a clear and direct set of instructions and explanations.
Amazon Verified review Amazon
Evony Apr 09, 2023
Full star icon Full star icon Full star icon Full star icon Full star icon 5
For starters, this book is worth so much more than the price shown. Since I already have extensive experience building apps with Vue.js 3, this book is a good source for solid documentation if you are a beginner to this JavaScript library.Secondly, this book incorporates up to date tools such as vite and the composition API. It even covers complex state management so no matter if you’re building large or small, this book scales with the project scope.It is extremely thorough with the examples that it provides. This is truly a resource that I would recommend for any front end developer who is building with Vue because you really don’t need anything else.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela