• vue3:vue3+vite+ts+pinia(配置详细)


    一、背景

    记录一套技术方案。

    二、项目基础

    2.1、创建项目

    yarn create vite

     输入名字后,这里出现了几个选项,不清楚都是干啥的,下来研究

     

    选择后完成

    2.2、vite.config.ts 配置alias:

    1. import { defineConfig } from 'vite'
    2. import vue from '@vitejs/plugin-vue'
    3. import { resolve } from 'path'
    4. // https://vitejs.dev/config/
    5. export default defineConfig({
    6. plugins: [vue()],
    7. resolve: {
    8. alias: {
    9. '@': resolve(__dirname, 'src')
    10. }
    11. }
    12. })

    2.3、安装element-plus

    https://element-plus.gitee.io/zh-CN/guide/installation.html#%E4%BD%BF%E7%94%A8%E5%8C%85%E7%AE%A1%E7%90%86%E5%99%A8

    2.4、配置环境变量:

    CSDN

    2.5、配置router

    vite2+vue3+TS+vue-router_ChenNianA的博客-CSDN博客

    https://www.jianshu.com/p/5f0301bca0ed

    2.6、安装husky

    【Vue】EsLint+Husky 实现代码提交时自动校验_夜雨Gecer的博客-CSDN博客_husky vue

    2.7、安装sass

    安装后重启项目

    npm install sass sass-loader -D

    经过测试不需要安装sass-loader,安装了会报错

    2.8、使用pinia

    学习Pinia 第一章(介绍Pinia)_小满zs的博客-CSDN博客

    2.9、使用cookie

    安装cookie

    pnpm add @types/js-cookie

    pnpm add js-cookie

    页面引入

    import cookie from 'js-cookie'

    使用cookie 

    1. const token = `Bearer ${cookie.get('token')}`
    2. console.log('16', token)

     使用成功

    2.10、处理问题:

    解决方法: 

    1. {
    2. "compilerOptions": {
    3. "target": "ESNext",
    4. "useDefineForClassFields": true,
    5. "module": "ESNext",
    6. "moduleResolution": "Node",
    7. "strict": true,
    8. "jsx": "preserve",
    9. "sourceMap": true,
    10. "resolveJsonModule": true,
    11. "isolatedModules": true,
    12. "esModuleInterop": true,
    13. "lib": ["ESNext", "DOM"],
    14. "skipLibCheck": true,
    15. "baseUrl": "./",
    16. "paths": {
    17. "@/*": ["src/*"]
    18. }
    19. },
    20. "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
    21. "references": [{ "path": "./tsconfig.node.json" }]
    22. }

    问题得到处理,不报错了 

    2.11、请求接口:

    类型限制:

    定义

     使用:

    参数要一致,不一致就会报错

     报错如图

    2.12、get请求传递参数:

    1. // 定义请求方法
    2. export const getUser = (data: T.userParams) => {
    3. return axios({
    4. method: "get",
    5. url: "/abc/getCompanyListByUser",
    6. data,
    7. config: {
    8. timeout: 10000
    9. }
    10. })
    11. }
    12. // 业务文件---直接和post方法一样的传递参数即可
    13. import { getUser } from "@/api/m-staff-center";
    14. let params = {
    15. keyword:"snow",
    16. }
    17. getUser(params).then((res: any)=>{
    18. console.log('4res', res)
    19. })

    这里已经得到了参数

     查看url已经有参数了,,查看查询结果,生效,ok

    2.13、prototype定义全局方法及使用

    1. import { getCurrentInstance } from 'vue'
    2. let internalInstance = getCurrentInstance();
    3. console.log(internalInstance.appContext.config.globalProperties.$api)

    vue 3.0 prototype 替代用法_寻ing的博客-CSDN博客_prototype vue3

     2.14、api Generators

    这种方式的优势,就是不需要每个业务文件都去引用具体的接口了,比较省事,个人推荐

    main.ts

    1. import { createApp } from 'vue'
    2. import './style.css'
    3. import App from './App.vue'
    4. import ElementPlus from 'element-plus'
    5. import 'element-plus/dist/index.css'
    6. import router from "./routers/index";
    7. import { api } from './api/index'
    8. const app = createApp(App)
    9. app.use(ElementPlus)
    10. app.use(router)
    11. app.config.globalProperties.$api = api // 全局定义属性
    12. app.mount('#app')

    目录:

    api/http/axios.ts

    1. import instance from "./index"
    2. /**
    3. * @param {String} method 请求的方法:get、post、delete、put
    4. * @param {String} url 请求的url:
    5. * @param {Object} data 请求的参数
    6. * @param {Object} config 请求的配置
    7. * @returns {Promise} 返回一个promise对象,其实就相当于axios请求数据的返回值
    8. */
    9. const axios = async ({
    10. method,
    11. url,
    12. data,
    13. config
    14. }: any): Promise<any> => {
    15. method = method.toLowerCase();
    16. if (method == 'post') {
    17. return instance.post(url, data, { ...config })
    18. } else if (method == 'get') {
    19. return instance.get(url, {
    20. params: data,
    21. ...config
    22. })
    23. } else if (method == 'delete') {
    24. return instance.delete(url, {
    25. params: data,
    26. ...config
    27. })
    28. } else if (method == 'put') {
    29. return instance.put(url, data, { ...config })
    30. } else {
    31. console.error('未知的method' + method)
    32. return false
    33. }
    34. }
    35. export {
    36. axios
    37. }

    api/http/index.ts

    1. import axios from 'axios'
    2. import cookie from 'js-cookie'
    3. //创建axios的一个实例
    4. var instance = axios.create({
    5. // baseURL: import.meta.env.VITE_RES_URL, //接口统一域名
    6. timeout: 6000, //设置超时
    7. headers: {
    8. 'Content-Type': 'application/json;charset=UTF-8;',
    9. }
    10. })
    11. //请求拦截器
    12. instance.interceptors.request.use((config: any) => {
    13. // 每次发送请求之前判断是否存在token,如果存在,则统一在http请求的header都加上token,不用每次请求都手动添加了
    14. const token = `Bearer ${cookie.get('token')}`
    15. console.log('16', token)
    16. token && (config.headers.Authorization = token)
    17. //若请求方式为post,则将data参数转为JSON字符串
    18. if (config.method === 'post') {
    19. config.data = JSON.stringify(config.data);
    20. } else if(config.method === 'get'){
    21. console.log('21', config)
    22. }
    23. return config;
    24. }, (error: any) =>
    25. // 对请求错误做些什么
    26. Promise.reject(error));
    27. //响应拦截器
    28. instance.interceptors.response.use((response: any) => {
    29. //响应成功
    30. console.log('响应成功');
    31. return response.data;
    32. }, (error: any) => {
    33. console.log(error)
    34. //响应错误
    35. if (error.response && error.response.status) {
    36. const status = error.response.status
    37. console.log(status);
    38. return Promise.reject(error);
    39. }
    40. return Promise.reject(error);
    41. });
    42. export default instance;

    api/index.ts

    1. import { axios } from './http/axios'
    2. const files:any = import.meta.globEager("./modules/*.ts") // 导入文件
    3. let api:any = {}
    4. let apiGenerators:any = [] // modules目录下文件内容的数组,每一个文件是一个{}
    5. for (const key in files) {
    6. if (Object.prototype.hasOwnProperty.call(files, key)) {
    7. apiGenerators.push(files[key].default)
    8. }
    9. }
    10. console.log('12apiGenerators', apiGenerators)
    11. apiGenerators.forEach((generator:any) => {
    12. const apiInstance = generator({ // 创建axios实例
    13. axios
    14. })
    15. for (const apiName in apiInstance) {
    16. if (apiInstance.hasOwnProperty(apiName)) {
    17. api[apiName] = apiInstance[apiName]
    18. }
    19. }
    20. })
    21. export { api }

    api/types/types.ts

    1. export interface userParams {
    2. keyword: string
    3. }

    api/modules/m-staff-center.ts

    1. import * as T from '../types/types'
    2. export default ({
    3. axios
    4. }:any) => ({
    5. getUser(data: T.userParams) {
    6. return axios({
    7. url: '/m-staff-center/api/v1/abc/getCompanyListByUser',
    8. data,
    9. method: "get"
    10. })
    11. },
    12. getUser2(data: T.userParams) {
    13. return axios({
    14. url: '/m-staff-center/api/v1/abc/getCompanyListByUser',
    15. data,
    16. method: "get"
    17. })
    18. },
    19. })

    业务文件使用:

    1. import { getCurrentInstance } from 'vue'
    2. let internalInstance = getCurrentInstance();
    3. let Api = internalInstance.appContext.config.globalProperties.$api
    4. let params = {
    5. keyword:"",
    6. }
    7. Api.getUser(params).then((res: any)=>{
    8. console.log('17res', res)
    9. })

     经过测试,请求成功

    2.15、vue-global-api

    安装:

    pnpm add vue-global-api

    main.ts引入 

    作用:

    使用vue-global-api 就无需像如下方式去引入了,Instead of import APIs from vue in every file
    import { ref, computed, watch } from 'vue'

    vue-global-api - npm

    2.16、reset.less

     2.17、uno.css(原子化css)

    Unocss(原子化css) 使用(vue3 + vite + ts)_全村d希望的博客-CSDN博客

    三、记录问题

    3.1、“NodeRequire”上不存在属性“context”

     解决:

    pnpm add @types/webpack-env

     亲测,成功。

    3.2、vue3+ts+vite2不适用require导入文件

    import.meta.globEager 

    https://www.jianshu.com/p/995e0670bb76

    3.3、对象可能为null

     解决:

    四、欢迎交流指正,关注我,一起学习。

    五、参考链接:

    Geeker-Admin/App.vue at master · HalseySpicy/Geeker-Admin · GitHub

    https://www.jianshu.com/p/3f5a413a296f

    pinia快速入门 (一) - 知乎

    什么是pinia?Vue中怎么使用它?-Vue.js-PHP中文网

    vite.config.js配置入门详解 - 威武的大萝卜 - 博客园

    Property 'context' does not exist on type 'NodeRequire' - 简书 (jianshu.com)

    (1条消息) 关于文件导入:required.context 和 vite Glob 导入_thingir的博客-CSDN博客

    最优雅解决typescript报错:“元素隐式具有 “any“ 类型,因为类型为 “string“ 的表达式不能用于索引类型”_皛心的博客-CSDN博客

  • 相关阅读:
    C - Minimize The Integer
    上海钢联朱军红:产业互联网的“双创”之路
    Flink的状态一致性
    2024年火爆全网的三款ai智能直播系统,你知道哪一种?
    类复习【C#】
    C++ STL进阶与补充(map/multimap容器)
    企业级springboot项目架构模板V5.0,开箱即用(针对中小型项目架构,免去重复造轮的操作,强烈推荐)
    02 【setup reactive ref】
    基于Solidworks的三维光路结构示意图绘制实例演示
    使用 Windows Core Audio APIs 进行 Loopback Recording 并生成 WAV 文件
  • 原文地址:https://blog.csdn.net/snowball_li/article/details/125001728