Frontend Engineering: Design and Practice Based on Vue.js 3.0

website·Indexed 32 days ago

https://vue3.chengpeiquan.com/

A comprehensive guide to Vue 3 development and frontend engineering. Covers essential topics including TypeScript integration, the Composition API with <script setup>, Pinia for state management, Vue Router, component communication, and plugin development. Includes instructions on project scaffolding with Vite, Node.js environment setup, and transitioning from Vue 2.

Tokens
38.2K
Snippets
222
Records
275
Agent score
79%

What's inside Vue 3

  1. Overview of Vue 3 component communication methods

    Depending on the relationship between components, different communication strategies should be used in Vue 3. Note that $listeners from Vue 2 has been removed.
    ScenarioParent $\rightarrow$ ChildChild $\rightarrow$ ParentMethod
    Parent-Childpropsemitsprops / emits
    Parent-Childv-modelemitsv-model / emits
    Parent-Childrefemitsref / emits
    Ancestor-Descendantprovideinjectprovide / inject
    Global/Cross-componentemit / onemit / onEventBus / Reactive State / Pinia / Vuex
  2. Understand the limitations of traditional frontend development

    Traditional frontend development relies on manually creating HTML files and linking JavaScript and CSS via <script> and <link> tags. This approach leads to several critical issues:

    1. Global Namespace Pollution: Variables declared with var in different files can overwrite each other if they share the same name. Variables declared with let or const will cause the application to crash with a SyntaxError if redeclared.
    2. Dependency Management: It is difficult to track where a variable was declared when multiple JS files are used, making large projects hard to maintain.
    3. Lack of Granularity: Utility libraries must often be imported in their entirety, increasing file size and blocking page rendering.
    4. Manual Optimization: Tasks like CSS minification and JS obfuscation must be performed manually, which is error-prone.
    5. Manual Resource Tracking: Managing resource references across multiple pages is tedious and leads to dependency chaos.
    <!-- Traditional approach: Risk of variable collision and ordering issues -->
    <script src="./js/lib-1.js"></script> <!-- var foo = 1 -->
    <script src="./js/lib-2.js"></script> <!-- var foo = 2 -->
    <script>
      console.log(foo); // Outputs 2, potentially breaking logic expecting 1
    </script>
  3. Understand the role of Node.js in frontend engineering

    Node.js is a JavaScript runtime built on the Chrome V8 engine that allows JavaScript to execute outside the browser (e.g., on servers or client-side tools). In modern frontend engineering, Node.js is essential because it enables the use of build tools and compilers (like Babel) to transform modern JS (ES6+) into browser-compatible ES5, allowing developers to use the latest language features without worrying about legacy browser compatibility.
  4. Manage global state with Pinia in Vue 3

    Pinia is the officially recommended state management tool for Vue 3 projects, serving as a modern alternative to Vuex. Key capabilities include:

    • Batch updating state
    • Full state updates
    • Resetting state
    • Subscribing to state changes
  5. Understand Development vs Production environments in build tools

    Build tools distinguish between 'development' and 'production' environments. This is distinct from business deployment stages (e.g., Test -> Pre-release -> Production); for a build tool, any stage requiring a final build for deployment is considered 'production'.

    Development Environment:

    • Supports TypeScript and CSS preprocessors.
    • Provides Hot Module Replacement (HMR) for instant updates without page refreshes.
    • Code is not minified and includes Source Maps for debugging.
    • Typically provides a local network service for easy access.

    Production Environment:

    • Code is compiled to the most compatible browser versions using Polyfills.
    • Code is minified and obfuscated to reduce bundle size and protect source code.
    • Highly stable; changes to source code do not affect the deployed version until a new build is executed.
  6. Understand the benefits of Vue's data-driven programming vs native DOM manipulation

    Vue uses a "data-driven" approach where updating a variable automatically synchronizes the view. In contrast, native JavaScript requires manual DOM manipulation, which is error-prone and can lead to performance issues due to frequent browser reflows and repaints. Vue optimizes this by using a Virtual DOM (VDOM)—a JavaScript object representation of the UI. When data changes, Vue uses a Diff algorithm to identify only the necessary changes in the VDOM before updating the real DOM, significantly reducing rendering overhead.
    <!-- Native JS approach: Manual DOM updates -->
    <p>Hello <span id="name"></span>!</p>
    <script>
      const nameElement = document.querySelector('#name');
      function handleInput() { 
        nameElement.innerText = inputElement.value; 
      }
    </script>
  7. Use TypeScript Type Assertions

    Type assertions allow you to tell the TypeScript compiler that you know more about a value's type than it can infer. Use the as keyword to specify a type. However, avoid overusing assertions; only use them when you can guarantee the code is correct, as assertions bypass the compiler's type checking and can lead to incomplete data objects if properties are missing.
    // Example: Asserting a return value as a string array
    function greet(name: string | string[]): string | string[] {
      if (Array.isArray(name)) {
        return name.map((n) => `Welcome, ${n}!`)
      }
      return `Welcome, ${name}!`
    }
    
    const greetings = greet(['Petter', 'Tom', 'Jimmy']) as string[]
    const greetingSentence = greetings.join(' ')
  8. Use PascalCase for components to support Tree Shaking

    While some UI frameworks (like Ant Design Vue) demonstrate global registration using kebab-case in templates (e.g., <a-select-option />), it is recommended to use PascalCase in your development habit. This makes it easier to identify the corresponding component for on-demand imports (e.g., <SelectOption />), which allows build tools to perform Tree Shaking and remove unused components from the final bundle.
    // On-demand import based on PascalCase naming
    import { Select, SelectOption } from 'ant-design-vue'
  9. Verify Node.js version compatibility for npm package build tools

    Before developing an npm package, verify that your current Node.js version is within the supported range of the build tools you are using to avoid compilation or runtime errors.
  10. Choose a Node.js server framework based on project scale

    Node.js server frameworks can be categorized into lightweight and enterprise-grade based on the project's architectural needs:

    1. Lightweight Frameworks: Best for small projects, simple static file serving (e.g., serving a built Vue project), or rapid prototyping. Examples include Express, Koa, and Fastify. These are 'fast and simple' but can become difficult to maintain in large teams without strict architectural discipline.
    2. Enterprise-Grade Frameworks: Best for large-scale projects requiring structured code layering and MVC architecture. These provide built-in 'Building Blocks' like TypeORM, WebSockets, and Swagger. Examples include Nest (built on Express/Fastify) and Egg (built on Koa).
  11. Install and manage packages using cnpm

    cnpm is a package manager by Alibaba that defaults to the npmmirror registry. It must be installed globally via npm before use. Note that cnpm does not generate or recognize lock files.
    # Install cnpm globally
    npm install -g cnpm
    
    # Alternative installation with explicit registry
    npm install -g cnpm --registry=https://registry.npmmirror.com
    
    # Install a package using cnpm
    cnpm install vue-router
  12. Use <script setup> for efficient Vue 3 component development

    The <script setup> syntax is a compiler macro for Vue 3 components (available in version 3.2.0+) that reduces boilerplate by eliminating the need to manually return variables and functions to the template. All top-level variables and functions defined within <script setup> are automatically exposed to the template. This approach is specifically designed for .vue files in engineered projects.
    <template>
      <p>{{ msg }}</p>
    </template>
    
    <script setup lang="ts">
    const msg = 'Hello World!'
    </script>