All Projects → allan2coder → vue3-tutorial

allan2coder / vue3-tutorial

Licence: MIT license
Vue3.2、Vite、setup、echarts、composition API

Programming Languages

typescript
32286 projects
CSS
56736 projects
Vue
7211 projects
javascript
184084 projects - #8 most used programming language
HTML
75241 projects
shell
77523 projects

Projects that are alternatives of or similar to vue3-tutorial

fearless
A dashboard scaffolding based on Vue.js 3.x & TypeScript created by Vite.
Stars: ✭ 1,156 (+282.78%)
Mutual labels:  vue3, vite
howdyjs
一个包含Javascript插件、Vue3组件、Vue3指令的工具库
Stars: ✭ 77 (-74.5%)
Mutual labels:  vue3, vite
seezoon-stack
一款基于当前最前沿的前端(Vue3 + Vite + Antdv)和后台(Spring boot)实现的低代码开发平台。
Stars: ✭ 227 (-24.83%)
Mutual labels:  vue3, vite
vuejs-3-examples
Some examples of Vue.js 3.0.
Stars: ✭ 26 (-91.39%)
Mutual labels:  vue3, vite
json-to-go
将json生成go的数据结构。Online tool that convert JSON to Go.
Stars: ✭ 16 (-94.7%)
Mutual labels:  vue3, vite
tailwind-layouts
Collection of Tailwind Layouts
Stars: ✭ 53 (-82.45%)
Mutual labels:  vue3, vite
electron-vite-tailwind-starter
This Starter utilizes Electron, Vite and Tailwindcss in combination. It trys to adhare best practices.
Stars: ✭ 141 (-53.31%)
Mutual labels:  vue3, vite
rustplatz
(Inoffizielle) Website für das Rust-Projekt von Dhalucard, Bonjwa und RocketBeans
Stars: ✭ 15 (-95.03%)
Mutual labels:  vue3, vite
Vue
Vue 使用指南,参照官方,结合自己的理解的一个记录。
Stars: ✭ 25 (-91.72%)
Mutual labels:  vue3, vite
vue-components-lib-seed
🌱 a vue3.0 components library template. Vue3.0 组件库的次佳实践.
Stars: ✭ 153 (-49.34%)
Mutual labels:  vue3, vite
nuxt3-tailwind
nuxt3 boilerplate with tailwind and dynamic routes.
Stars: ✭ 52 (-82.78%)
Mutual labels:  vue3, vite
vue3-element-admin
🎉 基于 vite2 + vue3 + element-plus 的后台管理系统vue3-element-admin;使用vue-cli可以切换webpack分支
Stars: ✭ 79 (-73.84%)
Mutual labels:  vue3, vite
mosha-vue-toastify
A light weight and fun Vue 3 toast or notification or snack bar or however you wanna call it library.
Stars: ✭ 185 (-38.74%)
Mutual labels:  vue3, vite
vite-vue3-tailwind
Boilerplate at vue 3 whit firebase, vue notus, typesctip, vite, tailwind
Stars: ✭ 21 (-93.05%)
Mutual labels:  vue3, vite
app
专门为互联网人打造的题解神器,神器在手,工作不愁
Stars: ✭ 64 (-78.81%)
Mutual labels:  vue3, vite
bpmn-vue-activiti
基于Vue3.x + Vite + bpmn-js + element-plus + tsx 实现的Activiti流程设计器(Activiti process designer based on Vue3.x + Vite + BPMN-JS + Element-Plus + TSX implementation)
Stars: ✭ 345 (+14.24%)
Mutual labels:  vue3, vite
preview-pro
Use pro-layout in vitejs. preview https://sendya.github.io/preview-pro/index.html
Stars: ✭ 71 (-76.49%)
Mutual labels:  vue3, vite
vueuse-vite-starter
⚡️ Starter for Vite + VueUse + TypeScript
Stars: ✭ 121 (-59.93%)
Mutual labels:  vue3, vite
rgutil
rgutil是基于ES6创建的函数库工具
Stars: ✭ 22 (-92.72%)
Mutual labels:  vue3, vite
vitailse
Opinionated Vite starter template with TailwindCSS
Stars: ✭ 95 (-68.54%)
Mutual labels:  vue3, vite

vue3-h5-template

基于 vue3 + vite + nut ui + sass + viewport 适配方案 +axios 封装,构建手机端模板脚手架

启动项目

npm install

npm run dev

目录

配置多环境变量

package.json 里的 scripts 配置 dev dev:test dev:prod ,通过 --mode xxx 来执行不同环境

  • 通过 npm run dev 启动本地环境参数 , 执行 development
  • 通过 npm run dev:test 启动测试环境参数 , 执行 test
  • 通过 npm run dev:prod 启动正式环境参数 , 执行 prod
"scripts": {
    "dev": "vite",
    "dev:test": "vite --mode test",
    "dev:prod": "vite --mode production",
}

▲ 回顶部

viewport 适配方案

不用担心,项目已经配置好了 viewport 适配, 下面仅做介绍:

PostCSS 配置

下面提供了一份基本的 postcss 配置,可以在此配置的基础上根据项目需求进行修改

// https://github.com/michael-ciniawsky/postcss-load-config
module.exports = {
  plugins: {
    'postcss-px-to-viewport-8-plugin': {
      unitToConvert: 'px', // 要转化的单位
      viewportWidth: 375, // UI设计稿的宽度
      unitPrecision: 6, // 转换后的精度,即小数点位数
      propList: ['*'], // 指定转换的css属性的单位,*代表全部css属性的单位都进行转换
      viewportUnit: 'vw', // 指定需要转换成的视窗单位,默认vw
      fontViewportUnit: 'vw', // 指定字体需要转换成的视窗单位,默认vw
      minPixelValue: 1, // 默认值1,小于或等于1px则不进行转换
      mediaQuery: true, // 是否在媒体查询的css代码中也进行转换,默认false
      replace: true, // 是否转换后直接更换属性值
      exclude: [/node_modules/], // 设置忽略文件,用正则做目录名匹配
    },
  },
};

更多详细信息: vant

新手必看,老鸟跳过

很多小伙伴会问我,适配的问题, 因为我们使用的是 Vant UI,所以必须根据 Vant UI 375 的设计规范走,一般我们的设计会将 UI 图上传到蓝湖,我们就可以需要的尺寸了。下面就大搞普及一下 rem。

我们知道 1rem 等于 html 根元素设定的 font-sizepx 值。Vant UI 设置 rootValue: 37.5 , 你可以看到在 iPhone 6 下看到 ( 1rem 等于 37.5px ):

<html data-dpr="1" style="font-size: 37.5px;"> </html>

切换不同的机型,根元素可能会有不同的 font-size 。当你写 css px 样式时,会被程序换算成 rem 达到适配。

因为我们用了 Vant 的组件,需要按照 rootValue: 37.5 来写样式。

举个例子:设计给了你一张 750px * 1334px 图片,在 iPhone6 上铺满屏幕, 其他机型适配。

  • rootValue: 75 , 样式 width: 750px;height: 1334px; 图片会撑满 iPhone6 屏幕,这个时候切换其他机型,图片也会跟着撑满。
  • rootValue: 37.5 的时候,样式 width: 375px;height: 667px; 图片会撑满 iPhone6 屏幕。

也就是 iphone 6 下 375px 宽度写 CSS。其他的你就可以根据你设计图,去写对应的样式就可以了。

当然,想要撑满屏幕你可以使用 100%,这里只是举例说明。

<img class="image" src="https://www.sunniejs.cn/static/weapp/logo.png" />

<style>
  /* rootValue: 75 */
  .image {
    width: 750px;
    height: 1334px;
  }

  /* rootValue: 37.5 */
  .image {
    width: 375px;
    height: 667px;
  }
</style>

▲ 回顶部

nutUI 组件按需加载

Vite 构建工具,使用 vite-plugin-style-import 实现按需引入。

安装插件

npm i vite-plugin-style-import -D

vite.config.ts 设置

 plugins: [
     ...
     createStyleImportPlugin({
         resolves: [NutuiResolve()],
     }),
     ...
 ],

使用组件

项目在 plugins/nutUI.ts 下统一管理组件,用哪个引入哪个,无需在页面里重复引用

// 按需全局引入nutUI组件
import Vue from 'vue';
import { Button, Cell, CellGroup } from '@nutui/nutui';
export const nutUiComponents = [Button, Cell, CellGroup];

// 在main.ts文件中引入
nutUiComponents.forEach((item) => {
  app.use(item);
});

▲ 回顶部

Pinia 状态管理

下一代 vuex,使用极其方便,ts 兼容好

目录结构

├── store
│   ├── modules
│   │   └── user.js
│   ├── index.js

使用

<script lang="ts" setup>
  import { useUserStore } from '@/store/modules/user';
  const userStore = useUserStore();
  userStore.login();
</script>

▲ 回顶部

Vue-router

本案例采用 hash 模式,开发者根据需求修改 mode base

注意:如果你使用了 history 模式, vue.config.js 中的 publicPath 要做对应的修改

前往:vue.config.js 基础配置

import Vue from 'vue';
import { createRouter, createWebHistory, Router } from 'vue-router';

Vue.use(Router);
export const router = [
  {
    name: 'root',
    path: '/',
    redirect: '/home',
    component: () => import('@/layout/basic/index.vue'),
  },
];

const router: Router = createRouter({
  history: createWebHistory(),
  routes: routes,
});

export default router;

更多:Vue Router

▲ 回顶部

Axios 封装及接口管理

utils/request.js 封装 axios , 开发者需要根据后台接口做修改。

  • service.interceptors.request.use 里可以设置请求头,比如设置 token
  • config.hideloading 是在 api 文件夹下的接口参数里设置,下文会讲
  • service.interceptors.response.use 里可以对接口返回数据处理,比如 401 删除本地信息,重新登录
import axios from 'axios';
import store from '@/store';
import { Toast } from 'vant';
// 根据环境不同引入不同api地址
import { baseApi } from '@/config';
// create an axios instance
const service = axios.create({
  baseURL: baseApi, // url = base api url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
});

// request 拦截器 request interceptor
service.interceptors.request.use(
  (config) => {
    // 不传递默认开启loading
    if (!config.hideloading) {
      // loading
      Toast.loading({
        forbidClick: true,
      });
    }
    if (store.getters.token) {
      config.headers['X-Token'] = '';
    }
    return config;
  },
  (error) => {
    // do something with request error
    console.log(error); // for debug
    return Promise.reject(error);
  },
);
// respone拦截器
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();
    console.log('err' + error); // for debug
    return Promise.reject(error);
  },
);
export default service;

接口管理

src/api 文件夹下统一管理接口

  • 你可以建立多个模块对接接口, 比如 home.js 里是首页的接口这里讲解 user.js
  • url 接口地址,请求的时候会拼接上 config 下的 baseApi
  • method 请求方法
  • data 请求参数 qs.stringify(params) 是对数据系列化操作
  • hideloading 默认 false, 设置为 true 后,不显示 loading ui 交互中有些接口不需要让用户感知
import qs from 'qs';
// axios
import request from '@/utils/request';
//user api

// 用户信息
export function getUserInfo(params) {
  return request({
    url: '/user/userinfo',
    method: 'post',
    data: qs.stringify(params),
    hideloading: true, // 隐藏 loading 组件
  });
}

如何调用

// 请求接口
import { getUserInfo } from '@/api/user.js';

const params = {
  user: 'sunnie',
};
getUserInfo(params)
  .then(() => {})
  .catch(() => {});

▲ 回顶部

vite.config.ts 基础配置

如果你的 Vue Router 模式是 hash

publicPath: './',

如果你的 Vue Router 模式是 history 这里的 publicPath 和你的 Vue Router base 保持一直

publicPath: '/app/',
export default function ({ command }: ConfigEnv): UserConfigExport {
  const isProduction = command === 'build';
  return {
    server: {
      host: '0.0.0.0',
    },
    plugins: [
      vue(),
      vueJsx(),
      createStyleImportPlugin({
        resolves: [NutuiResolve()],
      }),
      eruda(),
      viteMockServe({
        mockPath: './src/mock',
        localEnabled: command === 'serve',
        logger: true,
      }),
    ],
    css: {
      preprocessorOptions: {
        scss: {
          // 配置 nutui 全局 scss 变量
          additionalData: `@import "@nutui/nutui/dist/styles/variables.scss";`,
        },
      },
    },
  };
}

▲ 回顶部

配置 alias 别名

resolve: {
    alias: [{
            find: 'vue-i18n',
            replacement: 'vue-i18n/dist/vue-i18n.cjs.js',
        },
        // /@/xxxx => src/xxxx
        {
            find: /\/@\//,
            replacement: pathResolve('src') + '/',
        },
        // /#/xxxx => types/xxxx
        {
            find: /\/#\//,
            replacement: pathResolve('types') + '/',
        },
    ],
},

▲ 回顶部

配置 proxy 跨域

server: {
    proxy: {
        '/api': {
            target: 'https://baidu.com',
            changeOrigin: true,
            rewrite: (path) => path.replace(/^\/api/, '')
        }
    }
},

▲ 回顶部

Eslint+Pettier+stylelint 统一开发规范

根目录下的.eslintrc.js.stylelint.config.js.prettier.config.js内置了 lint 规则,帮助你规范地开发代码,有助于提高团队的代码质量和协作性,可以根据团队的规则进行修改

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].