08 Vue3项目搭建后台管理系统-项目配置

指定组件的名称

setup 的script标签中 去指定组件名字

1. 安装

npm i vite-plugin-vue-setup-extend -D

2. 配置 vue.config.ts

import { defineConfig } from 'vite'
import VueSetupExtend from 'vite-plugin-vue-setup-extend'

export default defineConfig({
  plugins: [ VueSetupExtend() ]
})

3. 设置组件的名

`<script setup lang="ts" name="Person1232">`

elementPlus配置

1. 下载安装

# @element-plus/icons-vue elementplus图标库
npm install element-plus @element-plus/icons-vue

2. main.ts 全局注册

import { createApp } from 'vue';
import { createPinia } from 'pinia';
// 1. 引入 elementPlus
import ElementPlus from 'element-plus';
// ElementPLus 语言默认中文
import zhCn from 'element-plus/es/locale/lang/zh-cn';
// 2. 引入 elementPlus 样式
import 'element-plus/dist/index.css';

// 3. 全局注册 elementPlus 图标
import * as ElementPlusIconsVue from '@element-plus/icons-vue';

import App from './App.vue';
import router from './router';

const app = createApp(App);
app.use(createPinia());
app.use(router);
// 3. icon配置
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
  app.component(key, component);
}
// ElementPLus 语言默认中文
app.use(ElementPlus, {
  locale: zhCn,
});

// 4. 使用 elementPlus
app.use(ElementPlus);
app.mount('#app');

封装注册全局组件

将目录 src/components/hc/**/*.vue 中的组件自动注册到全局

1. 创建文件 src/components/index.ts

组件名:默认是组件的文件名

import type { App } from 'vue';
import path from 'path-browserify';
import { defineAsyncComponent } from 'vue';
import type { AsyncComponentLoader } from 'vue';

const componentsList = import.meta.glob('@/components/hc/**/*.vue');

export default {
  install(app: App) {
    for (const [key, value] of Object.entries(componentsList)) {
      // 组件名
      const name = path.basename(key, '.vue');
      app.component(name, defineAsyncComponent(value as AsyncComponentLoader));
    }
  },
};

2. 注册到全局 main.ts

//引入自定义插件对象:注册整个项目全局组件
import gloalComponent from '@/components';
app.use(gloalComponent);

3. 在目录 @/components/crm/**/*.vue 中创建自己的组件

组件 c-test.vue

<template>
  <h1>测试组件</h1>
</template>
// name建议设置
<script lang="ts" setup></script>

<style scoped lang="scss"></style>

4. 任意位置使用组件

<template>
  <c-test></c-test>
</template>

<script setup lang="ts"></script>

svg全局注册使用

1. 下载安装开发依赖

npm install vite-plugin-svg-icons -D
npm install fast-glob -D

2. vite.config.ts中配置插件

import { createSvgIconsPlugin } from 'vite-plugin-svg-icons'
import path from 'path'
export default () => {
  return {
    plugins: [
      createSvgIconsPlugin({
        // 指定要缓存的图标库文件夹
        iconDirs: [path.resolve(process.cwd(), 'src/assets/icons')],
       // 格式定义
        symbolId: 'icon-[dir]-[name]',
      }),
    ],
  }
}

3. 主文件引入 main.ts

// 配置 svg-icons
import 'virtual:svg-icons-register';

4. 封装全局组件 SvgIcon.vue

<template>
  <svg :width="width" :height="height" :fill="color">
    <use :xlink:href="prefix + name"></use>
  </svg>
</template>

<script lang="ts" setup>
defineProps({
  //xlink:href属性值的前缀
  prefix: {
    type: String,
    default: '#icon-',
  },
  //svg矢量图的名字
  name: String,
  //svg图标的颜色
  color: {
    type: String,
    default: '',
  },
  //svg宽度
  width: {
    type: String,
    default: '16px',
  },
  //svg高度
  height: {
    type: String,
    default: '16px',
  },
});
</script>

5. 任意组件中使用SVG图标

<!-- name是 src/assets/icons.editsvg 里面的svg 图片的名称 -->
<svg-icon name="edit" width="30px" height="30px"></svg-icon>

集成sass

1. 安装

安装完毕后,即可使用sass语法啦

 npm i sass sass-loader -D

设置 全局scss变量的引入

在vite.config.ts文件配置如下:

  css: {
    preprocessorOptions: {
      scss: {
        additionalData: `@import "@/assets/globalVariable.scss";@import "@/assets/index.scss";`, // 引入全局变量
      },
    },
  },

axios 二次封装

import axios from 'axios';
import { ElMessage } from 'element-plus';
// 引入 nprogress 进度条
import NProgress from '@/utils/nprogress';

// 创建axios实例
let requestAxios = axios.create({
  baseURL: import.meta.env.VITE_API_URL,
  headers: {
    'Content-type': 'application/json',
  },
  timeout: 5000,
});

//请求拦截器
requestAxios.interceptors.request.use((config) => {
  NProgress.start();
  // // 设置头部token
  // const accessToken = localStorage.getItem('accessToken');
  // if (accessToken) {
  //   config.headers.Authorization = accessToken;
  // }

  // 重新定义 url 链接
  config.url = config.data.qUrl || import.meta.env.VITE_SERVER + '?method52=' + config.url;
  return config;
});

//响应拦截器
requestAxios.interceptors.response.use(
  (response) => {
    NProgress.done();
    if (!response.data.success) {
      // 请示失败 , 弹出报错信息:如果是登录失效,不提示
      if (response.data.reason && response.data.reason.indexOf('登录已失效') == -1) {
        ElMessage.error(response.data.reason);
      }
    }
    if (response) return response && response.data;
  },
  (error) => {
    NProgress.done();
    ElMessage({
      type: 'error',
      message: '检查接口是否正确!',
    });
    return Promise.reject(error);
  }
);

//封装请求的api
const callapi = (method = 'GET', url: string, data = {}) => {
  return requestAxios({
    method,
    url,
    params: method === 'GET' ? data : {},
    data: method === 'POST' ? data : {},
  });
};

// 封装GET请求函数
export const httpGet = (url: string, data = {}) => callapi('GET', url, data);

// 封装POST请求函数
export const httpPost = (url: string, data = {}) => callapi('POST', url, data);

接口调用

<script setup lang="ts">
import { onMounted } from 'vue';
import { httpGet, httpPost } from '@/utils/request';

let getTest = async () => {
  const res = await httpGet('b.member.getmember', { name: '00' });
  console.log(res, '请求的数据');
};

let postTest = async () => {
  const res = await httpPost('b.vod.getmoduleclassify', { name: '00' });
  console.log(res, '请求的数据');
};

let otherTest = () => {
  httpPost('', { qUrl: '/webphp/hchan/hchan_update.php?version=1&from=sghc' }).then((res) => {
    console.log(res, '请求的数据');
  });
};

onMounted(() => {
  getTest();
  postTest();
  otherTest();
});
</script>

Pinia 数据持久化

1. 安装

npm i pinia-plugin-persistedstate

2. 配置

文件 /src/stores/index.ts

import type { App } from 'vue';
import { createPinia } from 'pinia';
// 1. 引入 数据持久化
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate';

const store = createPinia();
// 2. 挂载使用
store.use(piniaPluginPersistedstate);

// 全局注册 store
export function setupStore(app: App<Element>) {
  app.use(store);
}

// 模块
export * from '@/stores/modules/user';
export { store };

3. 模块开启持久化

const useHomeStore = defineStore("home",()=>{
...
},
  // defineStore 第三个参数
  {
    // 添加配置开启 state/ref 持久化存储
    // 插件默认存储全部 state/ref
    persist: true,
  }
);


// 指定数据 持久化--推荐
  {
    persist: {
      key: 'userInfoStore', // 名称
      paths: ['userInfo'], // 指定 state 中哪些数据需要被持久化, 默认undefined
    },
  }

将自定义的工具方法挂载到全局

1. 定义自定义的方法等

# src/utils/index.ts 文件
export default {
  test1() {
    console.log('测试全局1');
  },
  test2() {
    console.log('测试全局2');
  },
};

2. 挂载到全局

# main.ts 文件

// 引入
import utilsTool from '@/utils';

// 挂载
app.provide('utilsTool', utilsTool);

3. 使用 inject 接收

import { inject } from 'vue';
const utilTools = inject('utilTools',<any>{});

utilTools.test1();
utilTools.test2();

posted @ 2024-04-17 14:18  songxia777  阅读(122)  评论(0编辑  收藏  举报