Skip to content

Latest commit

 

History

History
86 lines (58 loc) · 3.24 KB

course-single-file-components.md

File metadata and controls

86 lines (58 loc) · 3.24 KB

Single File Components

First, you read the official documentation on the topic here for Vue 3 or there for Vue 2.

Simply said, we will use a SingleFileComponent.vue file where the template, component script and its CSS will live.

What are Single File Components

They can be:

  • Views, also called pages, placed under the src/views or src/pages directory in a typical Vue project structure.
  • Components, placed under the src/components directory in a typical Vue project structure.

Reminder: In most projects, component names should always be PascalCase in Single-File Components and string templates - but kebab-case in in-DOM templates (what is in-DOM templates).

About scoped styles

Never style HTML elements directly, as it is a bad practice because it cause really bad performance in the browser.

<style lang="css" scoped>
  /*Your CSS code*/
</style>

Scoped-styles can be SCSS, LESS or SASS also. Just change the lang attribut accordingly.

See this article on the topic of CSS selector performance.

Organize the components

It is not recommended to organize components into folders and subfolders under src/components.

Instead, use a flat organization approach and follow naming best practice in the Vue style guide:

Code splitting for performance and bandwidth efficiency

For page and routes

With webpack, it is as easy as using it this way in the router:

  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  }

With Vite, no magic comment, just a dynaminc import :

const UserLoginRoute: RouteRecordRaw = {
  path: RoutePath.UserLogin,
  name: RouteName.UserLogin,
  component: () => import("@/pages/UserLogin.vue"),
};

For conditionnally displayed components

Since a child component may not always be displayed in the UI by default, it is a good idea not to load it in the parent chunk.

For example, when a user action is required, it is recommended to lazy load the component.

Using Webpack, you'll need to use the same methods but in the parent component's code:

  components: {
    BigYellowUsername: () =>
      import(
        /* webpackChunkName: "BigYellowUsername" */ "@/components/BigYellowUsername.vue"
      ),
  },

Note: chunks may tagged prefectch by default in the generated HTML.