Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Frontend Development Projects with Vue.js 3 - Second Edition
Frontend Development Projects with Vue.js 3 - Second Edition

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

By Maya Shavin , Raymond Camden , Clifford Gurney , Hugo Di Francesco
$39.99 $27.98
Book Mar 2023 628 pages 2nd Edition
eBook
$39.99 $27.98
Print
$49.99
Subscription
$15.99 Monthly
eBook
$39.99 $27.98
Print
$49.99
Subscription
$15.99 Monthly

What do you get with eBook?

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

Product Details


Publication date : Mar 17, 2023
Length 628 pages
Edition : 2nd Edition
Language : English
ISBN-13 : 9781803234991
Category :
Table of content icon View table of contents Preview book icon Preview Book

Frontend Development Projects with Vue.js 3 - Second Edition

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.

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

What do you get with eBook?

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

Product Details


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

Table of Contents

20 Chapters
Preface Chevron down icon Chevron up icon
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

Filter icon Filter
Top Reviews
Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(2 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


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 image
Nicolas Alexander Rau Nov 4, 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 image
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

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

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

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

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

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

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

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

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

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

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

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

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

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

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