vue3+vite+ts+pinia+router4 (一)vue3项目初始化

使用vite搭建项目

Vite 需要 Node.js 版本 18+,20+。然而,有些模板需要依赖更高的 Node 版本才能正常运行,当你的包管理器发出警告时,请注意升级你的 Node 版本。

话不多说直接来

npm install -g pnpm 
pnpm create vite my-vue3-ts --template vue-ts
cd my-vue3-ts
pnpm install
pnpm run dev

配置@别名

vite.config.ts

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path'
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  //这里进行配置别名
  resolve: {
    alias: {
      '@': path.resolve('./src'), // @代替src
    },
  },
})

tsconfig.json

{
  "compilerOptions": {
    "target": "ES2020",
    "useDefineForClassFields": true,
    "module": "ESNext",
    "lib": ["ES2020", "DOM", "DOM.Iterable"],
    "skipLibCheck": true,

    /* Bundler mode */
    "moduleResolution": "bundler",
    "allowImportingTsExtensions": true,
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve",

    /* Linting */
    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noFallthroughCasesInSwitch": true,

    "baseUrl": ".", // 查询的基础路径
    "paths": { "@/*": ["src/*"] } // 路径映射,配合别名使用
  },
  "include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
  "references": [{ "path": "./tsconfig.node.json" }]
}

这时候path报错未找到模块 安装下面的依赖

@types/node 是一个 TypeScript 类型定义文件的包,主要用于提供 Node.js API 的类型定义

pnpm install @types/node --save-dev

项目格式化工具 Prettier - Code formatter

在vscode中安装插件

配置 .prettierrc.cjs

module.exports = {
  // 一行最多多少字符
  printWidth: 200,
  // 使用 2 个空格缩进
  tabWidth: 2,
  // 不使用缩进符,而使用空格
  useTabs: false,
  // 行尾是否需要有分号。false 表示换行时,不要有分号,true 表示换行时,要有分号
  semi: false,
  // 使用单引号
  singleQuote: true,
  // 在 JSX 中使用单引号
  jsxSingleQuote: true,
  // 对象的 key 仅在必要时用引号
  quoteProps: 'as-needed',
  // 换行符使用 lf
  endOfLine: 'lf',
  // 强制在括号内使用一致的空格
  bracketSpacing: true,
  // 箭头函数,尽可能不用括号
  arrowParens: 'avoid',
  // 尾随逗号, 'none': 不要有尾随逗号, 'es5': 在 ES5 模式下要有尾随逗号, 'all': 在所有情况下都要有尾随逗号
  trailingComma: 'all',
  // 使用默认的折行标准
  proseWrap: 'preserve',
}

安装sass

pnpm install sass -D

删除 style.css

在src下新建styles

1709804417196.jpg

reset.scss

/* 
  Reset style sheet
*/
html,
body,
div,
span,
applet,
object,
iframe,
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote,
pre,
a,
abbr,
acronym,
address,
big,
cite,
code,
del,
dfn,
em,
img,
ins,
kbd,
q,
s,
samp,
small,
strike,
strong,
sub,
sup,
tt,
var,
b,
u,
i,
center,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td,
article,
aside,
canvas,
details,
embed,
figure,
figcaption,
footer,
header,
hgroup,
menu,
nav,
output,
ruby,
section,
summary,
time,
mark,
audio,
video {
  padding: 0;
  margin: 0;
  font: inherit;
  font-size: 100%;
  vertical-align: baseline;
  border: 0;
}

/* HTML5 display-role reset for older browsers */
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
menu,
nav,
section {
  display: block;
}
body {
  padding: 0;
  margin: 0;
}
ol,
ul {
  list-style: none;
}
blockquote,
q {
  quotes: none;
}
blockquote::before,
blockquote::after,
q::before,
q::after {
  content: '';
  content: none;
}
table {
  border-collapse: collapse;
  border-spacing: 0;
}
html,
body,
#app {
  width: 100%;
  height: 100%;
}

common文件定义公共样式

index.scss

@import './reset.scss'; // 初始化样式scss
@import './common.scss'; // 公共样式scss

在main.ts中引入

import { createApp } from 'vue'
import '@/styles/index.scss' // 全局样式
import App from './App.vue'
createApp(App).mount('#app')

安装路由 Vue Router 4.x

pnpm i vue-router@4

在src中新建router

1709805543118.jpg

router/index.ts

import {
  RouteRecordRaw,
  Router,
  createRouter,
  createWebHistory,
  createWebHashHistory,
} from "vue-router";
let routes: RouteRecordRaw[] = [
  {
    path: "/login",
    name: "Login",
    component: () => import("@/views/login/index.vue"),
  },
];
// 路由实例
// history
// const router: Router = createRouter({ history: createWebHistory(), routes });
// hash #
const router: Router = createRouter({
  history: createWebHashHistory(),
  routes,
});

export default router;

在main.ts中挂载router

import { createApp, App } from "vue";
import "@/styles/index.scss"; // 全局样式
import APP from "./App.vue";

const app: App = createApp(APP); // 创建vue实例
import router from "@/router"; // 注册路由

app.use(router)
app.mount("#app");

新建views/login/index.vue 文件

修改app.vue

<template>
  <router-view></router-view>
</template>

这样就可以访问 http://localhost:5173/#/login

安装pinia

pnpm i pinia
pnpm i pinia-plugin-persistedstate // 数据持久化插件

Snipaste_2024-03-07_19-22-10.png

store/index.ts

import { createPinia } from 'pinia'
const pinia = createPinia()
// pinia-plugin-persistedstate 插件
import piniaPluginPersistedstate from 'pinia-plugin-persistedstate'
pinia.use(piniaPluginPersistedstate)
export default pinia

在main.ts引入

import pinia from '@/store' // 注册Pinia
app.use(pinia)

在modules下面的文件在后面登录会涉及到

安装 element-plus

pnpm i element-plus

在main.ts引入

import ElementPlus from 'element-plus' // ElementPlus
import 'element-plus/dist/index.css' // ElementPlus样式
app.use(ElementPlus)

封装axios

pnpm i axios

新建utils/request.ts

Snipaste_2024-03-07_19-40-44.png
reques.ts

简单的封装了axios

import axios from "axios";
import type {
  AxiosInstance,
  AxiosResponse,
  InternalAxiosRequestConfig,
} from "axios";
const instance: AxiosInstance = axios.create({
  baseURL: "", // 基础 URL
  timeout: 50000, // 请求超时时间
});
// 请求拦截器
instance.interceptors.request.use(
  // AxiosRequestConfig 类型CreateAxiosDefaults不能赋值给AxiosRequestConfig
  (config: InternalAxiosRequestConfig) => {
    // 在请求发送之前可以做一些处理,比如添加请求头等
    return config;
  },
  (error: any) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);
// 响应拦截器
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response;
    if (data.code === 401) {
    }
    if (data.code !== 200) {
      return Promise.reject(data);
    }
    // 对响应数据做点什么
    return data;
  },
  (error: any) => {
    // 对响应错误做点什么
    return Promise.reject(error);
  }
);
export default instance;

到时候数据的话 到时候会手撸一个node+express+mongodb简单的后台服务 敬请期待!!

最后

欢迎 点赞 收藏 有问题欢迎留言评论!!

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
对于使用 Vite + Vue3 + TypeScript + Pinia + Vue Router + Axios + SCSS 并自动导入 API 的设置,你可以按照以下步骤进行操作: 1. 首先,确保你已经安装了 Node.js,并且版本大于等于 12.0.0。 2. 创建一个新的 Vue 项目,可以使用 Vue CLI 或者手动创建一个空文件夹。 3. 在项目根目录下,打开终端并执行以下命令安装 Vite: ```bash npm init vite@latest ``` 按照提示选择你的项目配置,包括选择 Vue 3、TypeScript 和其他选项。 4. 进入项目目录并安装依赖: ```bash cd your-project-name npm install ``` 5. 安装 Pinia 插件: ```bash npm install pinia ``` 6. 创建一个 `src/store` 目录,并在其中创建 `index.ts` 文件,用于定义和导出你的 Pinia store。 ```typescript // src/store/index.ts import { createPinia } from 'pinia' export const store = createPinia() // 可以在这里定义你的 store 模块 ``` 7. 在项目根目录下创建 `src/api` 目录,用于存放 API 请求相关的文件。 8. 在 `src/api` 目录下创建一个 `index.ts` 文件,用于自动导入所有 API 文件。 ```typescript // src/api/index.ts const modules = import.meta.globEager('./*.ts') const apis: any = {} for (const path in modules) { if (path !== './index.ts') { const moduleName = path.replace(/^.\/|\.ts$/g, '') apis[moduleName] = modules[path].default } } export default apis ``` 这样,你就可以在 `src/api` 目录下创建各种 API 请求的文件,例如 `user.ts`: ```typescript // src/api/user.ts import axios from 'axios' export function getUser(id: number) { return axios.get(`/api/user/${id}`) } ``` 然后,在你的组件中使用自动导入的 API: ```typescript import { defineComponent, ref } from 'vue' import { useUserStore } from '@/store' import apis from '@/api' export default defineComponent({ setup() { const userStore = useUserStore() const userId = ref(1) const fetchUser = async () => { const response = await apis.user.getUser(userId.value) userStore.setUser(response.data) } return { userId, fetchUser, } }, }) ``` 以上就是使用 Vite + Vue3 + TypeScript + Pinia + Vue Router + Axios + SCSS 并自动导入 API 的基本设置。你可以根据自己的需求进一步配置和扩展。希望对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Endless-y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值