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

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.

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