Vue-H5-Template

website·Indexed 29 days ago

https://sunniejs.github.io/vue-h5-template/

A mobile H5 project template supporting both Vue 2 and Vue 3. The latest version is based on Vite 7, Vue 3.5, TypeScript 5.9, and Pinia. It includes built-in configurations for axios request encapsulation, i18n multi-language support, viewport/rem/vw adaptation schemes, and integrated linting with ESLint, Prettier, and Stylelint.

Tokens
13.1K
Snippets
71
Records
86
Agent score
75%

What's inside Vue-H5-Template

  1. Overview of integrated Vite plugins in vue-h5-template

    The vue-h5-template integrates several Vite plugins to enhance development and production builds. These plugins are configured in the build/vite/plugins/ directory. The integrated plugins include:

    • Auto-importing: unplugin-auto-import (API/functions) and unplugin-vue-components (components).
    • Optimization & Compression: vite-plugin-compression (Gzip compression), vite-plugin-imagemin (image compression), and rollup-plugin-visualizer (bundle analysis reports).
    • Mobile Development & Debugging: @zhaojjiang/vite-plugin-eruda (mobile console), vite-plugin-qrcode (QR code for mobile access), and @vitejs/plugin-basic-ssl (local HTTPS support).
    • Routing & Assets: vite-plugin-pages (dynamic route generation) and vite-plugin-svg-icons (SVG loading and auto-import).
    • Developer Experience: vite-plugin-mock (MockJS integration), vite-plugin-progress (build progress bar), and vite-plugin-restart (auto-restart on config change).
    • PWA: vite-plugin-pwa (Progressive Web App support).
  2. Overview of Vue-H5-Template

    Vue-H5-Template is a rapid development scaffold for mobile applications. It is built with a modern tech stack including Vite 7, Vue 3.5, TypeScript 5.9, and Pinia. It utilizes a viewport (VW) adaptation scheme for responsive mobile layouts and integrates three major mobile UI libraries: Vant, NutUI, and Varlet, which are configured for automatic on-demand imports.
  3. Vue H5 Template Technical Stack

    The Vue H5 Template is built using the following modern technology stack, maintained to stay synchronized with official updates: Vue 3.5, Vite 7, TypeScript 5.9, and Pinia.
    Vue 3.5 + Vite 7 + TypeScript 5.9 + Pinia
  4. Switch mobile adaptation from rem to vw

    To change the project's responsive unit from rem to vw, you need to install the postcss-px-to-viewport plugin, configure the PostCSS settings, and remove the legacy lib-flexible and postcss-pxtorem dependencies. This allows you to write styles in px while the build tool automatically converts them to vw based on the design draft width.
    npm install postcss-px-to-viewport -D
  5. Modify child component styles from a parent using deep selectors

    When a child component uses the scoped attribute, you can modify its styles from the parent component by using the deep selector >>>.
    <style scoped>
    .a >>> .b { /* styles for child component element .b */ }
    </style>
  6. Set up and run the vue-h5-template project

    To get the vue-h5-template project running locally, ensure your environment meets the minimum requirements: Node.js version 20.10.0 or higher and pnpm version 9.12.0 or higher. The process involves cloning the repository, installing dependencies via pnpm, and using the development script to start the project.
    # Clone the project
    git clone https://github.com/sunniejs/vue-h5-template
    
    # Enter the project directory
    cd vue-h5-template
    
    # Install dependencies
    pnpm install
    
    # Start the development server
    pnpm dev
    
    # Build for production
    pnpm build
    
    # Preview the production build
    pnpm preview
  7. Implement a Pinia store using the Composition API

    Define a Pinia store using the Composition API (Setup Store) by using ref for state and functions for actions/getters. Persistence is configured in the third argument of defineStore using the persist property.
    import { defineStore } from "pinia";
    import { ref } from "vue";
    import { loginPassword } from "@/api";
    
    export const useUserStore = defineStore(
      "user",
      () => {
        const token = ref("");
        const info = ref<Record<any, any>>({});
    
        const getUserInfo = () => info.value || {};
    
        const setInfo = (data: any) => {
          info.value = data ?? "";
        };
    
        const login = async () => {
          try {
            const res = await loginPassword();
            setInfo(res);
            token.value = res.token;
            return res;
          } catch (error) {
            console.error("Login failed", error);
            throw error;
          }
        };
    
        return { token, info, getUserInfo, setInfo, login };
      },
      {
        persist: {
          pick: ["token"],
          storage: localStorage,
        },
      },
    );
  8. Set up ESLint and Prettier in VS Code for Vue 2

    To maintain a unified development specification, install the following VS Code extensions: eslint, prettier, and vetur. Configure the editor to use the vue plugin (via Vetur) for formatting .vue files and prettier for all other file types.
  9. Manage API interfaces in a modular structure

    API requests should be managed within the src/api folder. By creating modular files (e.g., user.js, home.js), you can define specific request configurations.

    Key configuration options for API calls:

    • url: The endpoint path (appended to baseApi).
    • method: The HTTP method (e.g., 'post', 'get').
    • data: The request payload. Use qs.stringify(params) for serialization.
    • hideloading: Set to true to prevent the global loading UI from appearing for a specific request.
    import qs from "qs";
    import request from "@/utils/request";
    
    export function getUserInfo(params) {
      return request({
        url: "/user/userinfo",
        method: "post",
        data: qs.stringify(params),
        hideloading: true, // Hide loading component
      });
    }
  10. Encapsulate Axios with request and response interceptors

    The utils/request.js file provides a pre-configured Axios instance. It includes a request interceptor to handle global loading states (via Vant Toast) and attach authentication tokens to headers. The response interceptor handles global error states, such as clearing the loading UI and triggering a logout/page reload when a 401 (Unauthorized) status is received.
    import axios from "axios";
    import store from "@/store";
    import { Toast } from "vant";
    import { baseApi } from "@/config";
    
    const service = axios.create({
      baseURL: baseApi,
      withCredentials: true,
      timeout: 5000,
    });
    
    service.interceptors.request.use(
      (config) => {
        if (!config.hideloading) {
          Toast.loading({ forbidClick: true });
        }
        if (store.getters.token) {
          config.headers["X-Token"] = store.getters.token;
        }
        return config;
      },
      (error) => {
        return Promise.reject(error);
      }
    );
    
    service.interceptors.response.use(
      (response) => {
        Toast.clear();
        const res = response.data;
        if (res.status && res.status !== 200) {
          if (res.status === 401) {
            store.dispatch("fedLogOut").then(() => {
              location.reload();
            });
          }
          return Promise.reject(res || "error");
        } else {
          return Promise.resolve(res);
        }
      },
      (error) => {
        Toast.clear();
        return Promise.reject(error);
      }
    );
    
    export default service;
  11. Implement a dynamic configuration manager for environment variables

    To avoid restarting the project when changing configuration values, use a pattern where .env files only define the environment name (VUE_APP_ENV), and a JavaScript configuration directory handles the actual values. This allows for easier maintenance and better developer experience.
    // src/config/index.js
    // Dynamically require the config file based on the environment variable
    const config = require("./env." + process.env.VUE_APP_ENV);
    module.exports = config;
    
    // src/config/env.development.js
    module.exports = {
      title: "vue-h5-template",
      baseUrl: "http://localhost:9018",
      baseApi: "https://test.xxx.com/api",
      APPID: "xxx",
      APPSECRET: "xxx",
    };
  12. Manage UI component libraries in vue-h5-template

    The template includes multiple component libraries to provide an out-of-the-box experience. If specific libraries are not needed, they can be removed following the project's UI removal guide.