没有特别的幸运,那么就特别的努力!!!
vue3 + vite + ts + vant + axios + sass 移动端h5搭建新项目
vue3 + vite + ts + vant + axios + sass
vite官网:
搭建第一个 Vite 项目 (vite + vue + ts)
兼容性注意 Vite 需要 Node.js 版本 14.18+,16+。然而,有些模板需要依赖更高的 Node 版本才能正常运行,当你的包管理器发出警告时,请注意升级你的 Node 版本。
npm init vite@latest
yarn create vite
pnpm create vite
# npm 6.x
npm create vite@latest vite-vue3 --template vue
# npm 7+, extra double-dash is needed:
npm create vite@latest vite-vue3 -- --template vue
# yarn
yarn create vite vite-vue3 --template vue
# pnpm
pnpm create vite vite-vue3 --template vue
项目启动
cd vite-vue3
npm install
npm run dev
代码规范 (格式化、提示)
eslint
# 自动生成配置文件并安装下面四个依赖
npx eslint --init
# 或者手动创建文件
# npm i eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin eslint-plugin-vue -D
prettier
npm i prettier eslint-config-prettier eslint-plugin-prettier -D
创建prettier文件
module.exports = {
printWidth: 100,
tabWidth: 2,
useTabs: false,
singleQuote: true,
semi: true,
arrowParens: 'always',
endOfLine: 'auto',
vueIndentScriptAndStyle: true,
htmlWhitespaceSensitivity: 'strict',
};
配置eslintrc
module.exports = {
root: true,
env: {
browser: true,
es2021: true,
node: true,
},
extends: [
'eslint:recommended',
'plugin:vue/vue3-essential',
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
'prettier',
],
parser: 'vue-eslint-parser',
parserOptions: {
ecmaVersion: 'latest',
parser: '@typescript-eslint/parser',
sourceType: 'module',
},
plugins: ['vue', '@typescript-eslint', 'prettier'],
rules: {
'vue/multi-word-component-names': 'off',
'@typescript-eslint/no-var-requires': 'off',
},
};
配置 tsconfig
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"module": "ESNext",
"moduleResolution": "Node",
"strict": true,
"jsx": "preserve",
"sourceMap": true,
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true,
"lib": ["ESNext", "DOM"],
"skipLibCheck": true,
"allowJs": true,
"baseUrl": "./",
"paths": {
"@/*": ["src/*"],
}
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue"],
"references": [{ "path": "./tsconfig.node.json" }]
}
tsconfig.node.json
{
"compilerOptions": {
"composite": true,
"module": "ESNext",
"moduleResolution": "Node",
"allowSyntheticDefaultImports": true
},
"include": ["vite.config.ts", "config/index.ts"]
}
CSS 预处理器
less安装使用
npm install less
npm install less-loader
yarn add less less-loader
< style lang="less" scoped></ style>
sass安装使用
npm install -D sass sass-loader
yarn add sass sass-loader
<style lang="scss" scoped>
.home {
background-color: #eee;
height: 100vh;
}
</style>
vant 安装
vant3官网地址: 安装
npm i vant
yarn add vant
pnpm add vant
常规用法
import { createApp } from 'vue'
import './style.css'
import { Button } from 'vant';
import 'vant/lib/index.css';
import App from './App.vue'
const app = createApp(App)
app.use(Button);
app.mount('#app');
按需引入组件样式
npm i unplugin-vue-components -D
yarn add unplugin-vue-components -D
pnpm add unplugin-vue-components -D
配置插件 vite 的项目,在 vite.config.js 文件中配置插件:
import vue from '@vitejs/plugin-vue';
import Components from 'unplugin-vue-components/vite';
import { VantResolver } from 'unplugin-vue-components/resolvers';
export default {
plugins: [
vue(),
Components({
resolvers: [VantResolver()],
}),
],
};
使用组件
<template>
<van-button type="primary" />
</template>
Rem 布局适配
npm install -D postcss-pxtorem lib-flexible
yarn add postcss-pxtorem lib-flexible
根目录下面新建一个 postcss.config.js 文件
module.exports = {
plugins: {
'postcss-pxtorem': {
rootValue: 37.5,
propList: ['*'],
},
},
};
底部适配 - 对于ios系统
<meta
name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, viewport-fit=cover"
/>
<van-nav-bar safe-area-inset-top />
<van-number-keyboard safe-area-inset-bottom />
vue-router
1.安装
npm i vue-router@4
2.创建路由
import { createRouter, createWebHashHistory } from "vue-router";
import { routes } from "./routes";
const router = createRouter({
history: createWebHashHistory(),
routes,
});
router.beforeEach((to, from, next) => {
document.title = to.meta.title as string || '浙里普法'
next()
})
export default router;
import { RouteRecordRaw } from "vue-router";
export const routes: Array<RouteRecordRaw> = [
{
path: "/",
redirect: "/index",
},
{
path: "/index",
name: "Index",
component: () => import("../view/index.vue"),
meta: {
nav: true,
title: '首页'
}
},
];
3.挂载路由
import { createApp } from 'vue';
import App from './App.vue';
import router from './router/index';
const app = createApp(App);
app.use(router);
app.mount('#app');
4.使用
<template>
<router-view />
</template>
Axios
1.安装
npm i axios
yarn add axios
import axios, { AxiosResponse, AxiosRequestConfig, AxiosError } from 'axios';
import type { Response } from './types';
import { Toast } from 'vant';
import router from '../../router';
axios.defaults.baseURL = '/api';
axios.defaults.timeout = 1000 * 60;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
const service = axios.create({
baseURL: import.meta.env.VITE_APP_API_BASE_URL,
});
service.interceptors.request.use(
(config: AxiosRequestConfig) => {
config.headers = {
...config.headers,
};
return config;
},
(error: AxiosError) => {
return Promise.reject(error);
}
);
service.interceptors.response.use(
(response: AxiosResponse<Response>) => {
const { code, message } = response.data;
let errMessage = '';
switch (code) {
case 0:
break;
case 1:
errMessage = 'Token expired';
router.push('/login');
break;
case 2:
errMessage = 'No permission';
break;
}
if (errMessage) Toast.fail(errMessage);
return response;
},
(error: AxiosError) => {
Toast.fail('Network Error...');
return Promise.reject(error);
}
);
export type { AxiosResponse, AxiosRequestConfig };
export default service;
import service, { AxiosRequestConfig } from './axios';
export * from './types';
export const request = <T = any>(config: AxiosRequestConfig): Promise<T> => {
return new Promise((resolve, reject) => {
service
.request(config)
.then((res) => {
resolve(res.data);
})
.catch((err) => {
console.log('request fail:', err);
});
});
};
const http = {
get<T = any>(url: string, params = {}, config?: AxiosRequestConfig): Promise<T> {
return request({ url, params, ...config, method: 'GET' });
},
post<T = any>(url: string, data = {}, config?: AxiosRequestConfig): Promise<T> {
return request({ url, data, ...config, method: 'POST' });
},
put<T = any>(url: string, data = {}, config?: AxiosRequestConfig): Promise<T> {
return request({ url, data, ...config, method: 'PUT' });
},
delete<T = any>(url: string, data = {}, config?: AxiosRequestConfig): Promise<T> {
return request({ url, data, ...config, method: 'DELETE' });
},
upload<T = any>(url: string, data = {}, config?: AxiosRequestConfig): Promise<T> {
return request({
url,
data,
...config,
method: 'POST',
headers: { 'Content-Type': 'multipart/form-data' },
});
},
};
export default http;
export interface Response<T = any> {
data: string[];
code: number | string;
message: string;
result: T;
}
示例页面
banner列表页面
<script setup>
import ResourceList from '@/components/ResourceList.vue'
import { monthlyResourceList } from '@/service/api/common'
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from "vue-router";
const $route = useRoute()
const $router = useRouter()
const list = ref([])
const loading = ref(false);
const finished = ref(false);
const refreshing = ref(false);
const params = ref({
relationId: $route.query.id,
relationType: 'banner',
currentPage: 1,
pageSize: 10
})
onMounted(() => {
document.title = $route.query.name
getColumnResourceList()
})
const getColumnResourceList = () => monthlyResourceList(params.value).then(res => {
loading.value = true
if (res.success) {
loading.value = false
list.value = [...list.value,...res.data]
if (list.value.length >= res.totalCount) {
finished.value = true
}
}
})
const onRefresh = () => {
params.value.currentPage = 1
finished.value = false;
refreshing.value = false
list.value = []
getColumnResourceList();
};
const onLoad1 = () => {
params.value.currentPage++
getColumnResourceList()
}
const toInfo = row => {
const { type, resourceSource, resourceId, id: relationId, relationType = 'banner' } = row
$router.push({
path: '/detail',
query: { type, resourceSource, resourceId, relationId, relationType }
})
}
</script>
<template>
<div class='monthInfo'>
<van-pull-refresh v-model="refreshing" @refresh="onRefresh">
<van-list
v-model:loading="loading"
:finished="finished"
finished-text="没有更多了"
:immediate-check="false"
@load="onLoad1"
>
<div v-for="(item, i) in list" :key="i">
<ResourceList :info="item" @click="toInfo(item)"></ResourceList>
</div>
</van-list>
</van-pull-refresh>
</div>
</template>
<style lang='scss' scoped>
.monthInfo {
padding: 22px 16px;
}
</style>
项目地址
为了安全协议:项目地址api 已全部替换(望理解!!!) https://gitee.com/hammer1010_admin/vue3-vite
希望能帮助到大家,同时祝愿大家在开发旅途中愉快!!!
拿着 不谢 请叫我“锤” !!!
|