Vite+Vue常见组件整合备忘

98 阅读2分钟

搭建 Vue 3 + Vite 项目

# 使用vue模板,如果需要支持typescript,则使用vue-ts模板
pnpm create vite my-vue-admin --template vue

配置路径别名

import { resolve } from "path";
const pathSrc = resolve(__dirname, "src");
export default defineConfig(({ mode }) => {
  return {
    // 路径别名
    resolve: {
      alias: {
        '@': pathSrc,
      },
    },
    ...
  };
});

测试使用别名
import HelloWorld from './components/HelloWorld.vue'
import HelloWorld from '@/components/HelloWorld.vue'

按需自动导入API和组件

pnpm add -D unplugin-auto-import unplugin-vue-components

# 配置自动导入
plugins: [
    vue(),
    // 自动导入API
    AutoImport({
    // 导入 Vue 的 API
    imports: ['vue',],
    }),
    // 自动导入组件
    Components({
    // 指定自定义组件位置(默认:src/components)
    dirs: [
        'src/components/**',
        'src/**/components',
    ],
    }),
],

测试使用
<!-- src/components/HelloWorld.vue -->
// import { ref } from 'vue'

安装element-plus及自动导入

pnpm add element-plus

# 测试
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";

AutoImport({
    ...
    resolvers: [
        // 自动导入 Element Plus 相关函数,如:ElMessage, ElMessageBox... (带样式)
        ElementPlusResolver(),
    ],
}),
// 自动导入组件
Components({
    ... 
    resolvers: [
        // 自动导入 Element Plus 组件
        ElementPlusResolver(),
    ],
}),

# 测试
<!-- src/components/HelloWorld.vue -->
<div>
  <el-button type="success">Success</el-button>
  <el-button type="info">Info</el-button>
  <el-button type="warning">Warning</el-button>
  <el-button type="danger">Danger</el-button>
</div>

自动导入Icons图标

pnpm add -D unplugin-icons

# 配置
plugins: [
    AutoImport({
    resolvers: [
        // 自动导入图标组件
        IconsResolver({}),
    ],
    }),
    // 自动导入组件
    Components({
    resolvers: [
        // 自动注册图标组件
        IconsResolver({
        // element-plus图标库,其他图标库 https://icon-sets.iconify.design/
        enabledCollections: ["ep"]
        }),
    ],
    }),
    Icons({
    // 自动安装图标库
    autoInstall: true,
    }),
],

# 测试
<!-- src/components/HelloWorld.vue -->
<div>
  <el-button type="success"><i-ep-SuccessFilled />Success</el-button>
  <el-button type="info"><i-ep-InfoFilled />Info</el-button>
  <el-button type="warning"><i-ep-WarningFilled />Warning</el-button>
  <el-button type="danger"><i-ep-WarnTriangleFilled />Danger</el-button>
</div>

整合 SVG 图标

pnpm add -D vite-plugin-svg-icons

# 配置
import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'

createSvgIconsPlugin({
    // 指定需要缓存的图标文件夹
    iconDirs: [path.resolve(process.cwd(), 'src/icons')],
    // 指定symbolId格式
    symbolId: 'icon-[dir]-[name]',
}),

# 测试
参考: src\components\SvgIcon.vue

整合 SCSS

pnpm add -D sass

# 配置
    css: {
      preprocessorOptions: {
        scss: {
          javascriptEnabled: true,
          additionalData: `@use "@/assets/styles/global.scss" as *;`,
        },
      },
    },

# 测试
创建文件 "src/assets/style/global.scss"
$bg-color:#242424;

# src\components\HelloWorld.vue
<style lang="scss" scoped>
.read-the-docs {
  color: #888;
  background-color: $bg-color;
}
</style>

整合 UnoCSS

pnpm add -D unocss

# 配置
// src/main.ts
import 'uno.css'

// vite.config.ts
import UnoCSS from 'unocss/vite'

export default {
  plugins: [
    UnoCSS({ /* options */ }),
  ],
}

# 测试
# src\components\HelloWorld.vue
<div class="text-red">Hello World!!</div>

整合 Pinia

pnpm add pinia

# src/main.js
import { createPinia } from "pinia";
....use(createPinia())...

# 测试
# src/store/counter.ts
import { defineStore } from "pinia";

export const useCounterStore = defineStore("counter", () => {
  // ref变量 → state 属性
  const count = ref(0);
  // computed计算属性 → getters
  const double = computed(() => {
    return count.value * 2;
  });
  // function函数 → actions
  function increment() {
    count.value++;
  }

  return { count, double, increment };
});

# <!-- src/App.vue -->
import { useCounterStore } from "@/store/counter";
const counterStore  = useCounterStore();
...
<div>
    <h1>父组件</h1>
    <el-button @click="counterStore.increment">增加</el-button>
</div>

# <!-- src/components/HelloWorld.vue -->
<div>
    <h1>子组件</h1>
    <div>计数:{{ counterStore.count }}</div>
    <div>双倍:{{ counterStore.double }}</div>
</div>

env 配置文件

# 创建文件 .env.development
# .env.development:开发环境配置文件
# 变量必须以 VITE_ 为前缀才能暴露给外部读取

# 代理模式的后端服务器地址
VITE_APP_BASE_API=http://raiseinfo-admin.test
# WebSocket 端点
VITE_APP_WS_ENDPOINT=
# Mqtt 端点
VITE_APP_MQTT_ENDPOINT=ws://121.42.254.204:8083/mqtt

# 创建文件 .env.production
# .env.production: 生成环境配置文件
# 变量必须以 VITE_ 为前缀才能暴露给外部读取

VITE_APP_BASE_API=http://raiseinfo-admin.test
# WebSocket 端点
VITE_APP_WS_ENDPOINT=
# Mqtt 端点
VITE_APP_MQTT_ENDPOINT=ws://121.42.254.204:8083/mqtt

# 测试
server: {
  host: '0.0.0.0',
  port: env.VITE_PORT,
  open: true,
  proxy: {
    '/admin': {
      changeOrigin: true,
      target: env.VITE_HOST,
      rewrite: (path) => path.replace(new RegExp('^' + '/admin'), '/admin'),
    },
    '/upload': {
      changeOrigin: true,
      target: env.VITE_HOST,
      rewrite: (path) =>
        path.replace(new RegExp('^' + '/upload'), '/upload'),
    },
  },
},


整合 Axios

pnpm add axios