1.安装vite 及创建vue项目
npm install vite@latest
npm init @vitejs/app myproject2
//√ Select a framework: » vue
//√ Select a variant: » vue-ts
找到项目目录
npm install //安装依赖
vite //启动项目
2.UI框架选型:ant-desgin-vue & 按需引入,首屏加速
npm install ant-design-vue
npm install vite-plugin-imp@2.1.6
vite.config.ts
文件改动:
import vitePluginImp from 'vite-plugin-imp';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
vitePluginImp({ //增加配置项
libList: [
{
libName: "antd",
style: (name) => `antd/es/${name}/style`,
},
],
}),
],
css: {
}
})
项目src
目录下新增Antd.ts
文件:
import {
Input,
Button,
DatePicker,
} from "ant-design-vue";
export const antArr = [
Input,
Button,
DatePicker,
];
修改main.ts
文件:
import {antArr} from "./Antd";
const app = createApp(App);
//按需加载antd组件库
for (const item of antArr){
app.use(item);
}
app.mount('#app')
组件应用示例:
<a-button type="primary">啦啦啦</a-button>
3.vue-router
npm install vue-router
在src
目录下新建route index.ts
文件
import { createRouter, RouteRecordRaw, createWebHashHistory } from 'vue-router'
export const routes: RouteRecordRaw[]= [
{
path: '/',
component: () => import('../components/HelloWorld.vue')
},
{
path: '/demo',
component: () => import('../pages/TableDemo.vue')
},
];
const router = createRouter({
history: createWebHashHistory(), // hash路由模式
// history: createWebHistory(), // history路由模式
routes
});
export default router;
在main.ts
中引入route
import router from "./router";
...
app.use(router)
4.VSCODE开发遇到的问题
-
*** is declared but its value is never read.Vetur(6133)报错解决方法。
(问题解决参考原文地址:)
https://blog.csdn.net/boldiy/article/details/124611118
2.Ts里面使用const let
语法提示报错,修改tsconfig.json
为:
{
"compilerOptions": {
"target": "esnext",
"useDefineForClassFields": true,
"module": "esnext",
"moduleResolution": "node",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"noImplicitAny":false,//可选类型语言转换为强制类型检验语言,改为false在对象使用[]就不会报错
"resolveJsonModule": true,
"esModuleInterop": true,
"lib": ["esnext", "dom"],
"baseUrl": ".",
"paths": {
"@/*": [
"src/*"
]
},
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
"references": [{ "path": "./tsconfig.node.json" }]
}
5.axios请求封装
npm install axios
在src
目录下新增request
文件夹,新增index.ts
文件,封装axios
请求
import axios from 'axios'
import { message } from 'ant-design-vue'
const service = axios.create()
// request interceptor
service.interceptors.request.use(
config => {
config.headers = {
'accessToken': '16558812453532fd0929f05c64b10aa71ed2e7f674f42', //TODO
'appType': 'web',
'Content-Type': 'application/json;charset=UTF-8',
}
//老业务逻辑:GET 请求增加时间戳
if (config.method && config.method === 'get') {
var timestamp = new Date().getTime();
if (config.params) {
config.params.timestamp = timestamp;
} else {
config.params = {
timestamp: timestamp
}
}
}
//老业务逻辑:post请求,自定义Content-Type
if (config.data && config.data.headersContentType) {
config.headers['Content-Type'] = config.data.headersContentType;
}
return config
},
error => {
return Promise.reject(error)
}
)
service.interceptors.response.use(
response => {
const res = response.data
if (res.errorCode) {
message.error(res.errorDescription)
}
const responseStatus = response.status;
if (responseStatus === 200) {
return res
}
},
error => {
return Promise.reject(error)
}
)
export default service
统一封装定义请求api
import request from '@/request'
import { message } from 'ant-design-vue'
const BASE_URL_PORTAL = '/cloud-portal'
//获取用户基本信息
// export function getCurrentUserInfo(params: Object){
// return request({
// url: `${BASE_URL_PORTAL}/create/getCurrentUserInfo`,
// method: 'get',
// params
// }).catch(() => {
// message.error('接口异常');
// })
// }
export function getCurrentUserInfoApiFunc(params:Object){
return sendReuqest({
module: BASE_URL_PORTAL,
path:'/create/getCurrentUserInfo',
name:'获取用户信息',
params,
method:'get',
});
}
/**
*
* @param moudle 模块名称 例:'/cloud-portal'
* @param path 请求路径 例:'/create/getCurrentUserInfo'
* @param name 接口名称 例:'获取用户信息'
* @param params 接口传参 例:'{}'
* @param method 请求方式 例:'get'
*/
export interface RequestIn{
module:string,
path:string,
name:String,
params:Object,
method:any
}
export async function sendReuqest(req:RequestIn){
try {
return await request({
url: req.module + req.path,
method: req.method,
params: req.method === 'get' ? req.params : null,
data: req.method === 'post' ? req.params : null,
})
} catch {
message.error(req.name + '接口异常')
}
}
发送请求示例
getCurrentUserInfoApiFunc({}).then(resp => {
console.log('resp',resp)
})
6.pinia
引入
npm install pinia
在src
目录下新增store
文件夹,新增user.ts
文件
import { defineStore, acceptHMRUpdate } from "pinia";
export const useUserStore = defineStore({
id: "user", //每个store文件必须有个唯一的标志
state: () => ({
name:1
}),
actions: {
addName(){
this.name++;
},
},
});
// @ts-ignore,热更新的配置
if (import.meta.hot) {
import.meta.hot.accept(acceptHMRUpdate(useUserStore, import.meta.hot))
}
调用示例
import { useUserStore } from "@/store/user"
const userInfo = useUserStore()
//计算属性使用
let name = ref(computed(() => {
return userInfo.name;
}))
function add () {
userInfo.addName(); //方法调用
}