Reader small image

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

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

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

Raymond Camden
Raymond Camden
author image
Raymond Camden

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

Clifford Gurney
Clifford Gurney
author image
Clifford Gurney

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

Hugo Di Francesco
Hugo Di Francesco
author image
Hugo Di Francesco

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

View More author details
Right arrow

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.

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

Authors (4)

author image
Maya Shavin

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

author image
Raymond Camden

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

author image
Clifford Gurney

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

author image
Hugo Di Francesco

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