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

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

Product type Book
Published in Mar 2023
Publisher Packt
ISBN-13 9781803234991
Pages 628 pages
Edition 2nd Edition
Languages
Authors (4):
Maya Shavin Maya Shavin
Profile icon Maya Shavin
Raymond Camden Raymond Camden
Profile icon Raymond Camden
Clifford Gurney Clifford Gurney
Profile icon Clifford Gurney
Hugo Di Francesco Hugo Di Francesco
Profile icon Hugo Di Francesco
View More author details

Table of Contents (20) Chapters

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

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.

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