vite+ts+vue3+router4+Pinia+ElmPlus+axios+mock项目基本配置
1.vite+TS+Vue3
npm create vite
Project name:... yourProjectName
Select a framework:>>Vue
Select a variant:>>Typescrit
2. 修改vite基本配置
配置 Vite {#configuring-vite} | Vite中文网 (vitejs.cn)
vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import { resolve } from 'path'; // 编辑器提示 path 模块找不到,可以cnpm i @types/node --dev 即可
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()], // 默认配置
resolve: {
alias: {
'@': resolve(__dirname, 'src') // 配置别名;将 @ 指向'src'目录
}
},
server: {
port: 3000, // 设置服务启动的端口号;如果端口已经被使用,Vite 会自动尝试下一个可用的端口
open: true, // 服务启动后自动打开浏览器
proxy: { // 代理
'/api': {
target: '真实接口服务地址',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, '') // 注意代理地址的重写
},
// 可配置多个...
}
}
})
3.安装vue-router
cnpm install vue-router@4 --save
创建src/router/index.ts
文件,使用路由懒加载,优化访问性能。
import { createRouter, createWebHistory, createWebHashHistory, RouteRecordRaw } from 'vue-router'
const routes: Array<RouteRecordRaw> = [
{
path: '/',
name: 'Home',
component: () => import('@/views/home.vue') // 建议进行路由懒加载,优化访问性能
},
{
path: '/about',
name: 'About',
component: () => import('@/views/about.vue')
}
]
const router = createRouter({
// history: createWebHistory(), // 使用history模式
history: createWebHashHistory(), // 使用hash模式
routes
})
export default router
main.ts
里面引入router
import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'
createApp(App).use(router).mount('#app')
在App.vue
文件中使用router-view
组件,路由匹配到组件会通过router-view
组件进行渲染。
<template>
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
</div>
<router-view />
<template>
4.安装vuex 安装pinia
npm install vuex@next --save
创建src/store/index.ts
文件。
import { createStore } from 'vuex'
const defaultState = {
count: 0
}
const store = createStore({
state () {
return {
count: 10
}
},
mutations: {
increment (state: typeof defaultState) {
state.count++
}
}
})
export default store;
main.ts
里面引入vuex
import { createApp } from 'vue'
import App from './App.vue'
import router from './router/index'
import store from './store/index'
const app = createApp(App);
// 将store、router挂载到全局变量上, 方便使用
import { useStore } from "vuex";
import { useRoute } from "vue-router";
app.config.globalProperties.$store = useStore();
app.config.globalProperties.$router = useRoute();
app.use(router).use(store).mount('#app')
<template>
<div>
首页 {{count}}
<p @click="handleSkip">点我</p>
</div>
</template>
<script>
import { getCurrentInstance, computed, ref } from 'vue';
export default {
name: 'Home',
setup() {
const { proxy } = getCurrentInstance();
// 使用store
const count = computed(() => proxy.$store.state.count);
const handleSkip = () => {
// 使用router
proxy.$router.push('/about');
}
return {
count: ref(count),
handleSkip
}
}
}
</script>
pinia
yarn add pinia
# 或者使用 npm
npm install pinia
main.ts
import { createApp } from 'vue'
import './style.css'
import router from './router'
import { createPinia } from 'pinia'
import App from './App.vue'
createApp(App).use(router).use(createPinia()).mount('#app')
@/store/counter.ts
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
state: () => ({ count: 0 }),
getters: {
double: (state) => state.count * 2,
},
actions: {
increment() {
this.count++
},
},
})
Home.vue
<template>
<div><p>home</p>
<button @click="increment">count:{{count}};double:{{double}}</button>
</div>
</template>
<script setup lang="ts">
import { storeToRefs } from 'pinia';
import { useCounterStore } from '../store/counter';
const counter = useCounterStore()
const {count, double} = storeToRefs(counter)//这样才是响应式的
const {increment } = counter
</script>
<style scoped></style>
5.安装 UI库
1.Element UI Plus
NPM
$ npm install element-plus --save
import { createApp } from 'vue'
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import App from './App.vue'
const app = createApp(App)
app.use(ElementPlus)
app.mount('#app')
volar插件支持 获取对Element UI Plus 的提示 需要在tsconfig.json做如下设置
新增"types": ["element-plus/global"]
{
"compilerOptions": {
// ...
"types": ["element-plus/global"]
}
}
2.Ant Design Vue
Ant Design of Vue - Ant Design Vue (antdv.com)
$ npm install ant-design-vue@next --save
$ yarn add ant-design-vue@next
import { createApp } from 'vue';
import Antd from 'ant-design-vue';
import App from './App';
import 'ant-design-vue/dist/antd.css';
const app = createApp(App);
app.use(Antd).mount('#app');
3.Iview
npm install view-ui-plus --save
import { createApp } from 'vue'
import ViewUIPlus from 'view-ui-plus'
import App from './App.vue'
import router from './router'
import store from './store'
import 'view-ui-plus/dist/styles/viewuiplus.css'
const app = createApp(App)
app.use(store)
.use(router)
.use(ViewUIPlus)
.mount('#app')
4.Vant 移动端
npm i vant -S
import Vant from 'vant'
import 'vant/lib/index.css';
createApp(App).use(Vant).$mount('#app)
6.安装axios
npm install axios --save
封装公共请求方法
新建工具类 src/utils/request.ts
import axios from 'axios'
interface ApiConfig {
body: object;
data: object
}
async function request(url: string, options: ApiConfig) {
// 创建 axios 实例
const service = axios.create({
baseURL: "", // api base_url
timeout: 6000 // 请求超时时间
});
// 请求拦截
service.interceptors.request.use(config => {
// 这里可设置请求头等信息
if (options && options.body) {
config.data = options.body;
}
return config;
});
// 返回拦截
service.interceptors.response.use(response => {
// 这里可进行返回数据的格式化等操作
return response.data;
});
return service(url, options);
}
export default request;
使用方法
<script>
import request from "@/utils/request.ts"
export default {
setup() {
request('/api/getNewsList').then(res => {
console.log(res);
// to do...
});
}
}
</script>
7.安装mockjs
安装
mock
模拟数据我们选用 mockjs
插件,vite
中需要安装 vite-plugin-mock
插件。
npm install mockjs --save
npm install vite-plugin-mock --save-dev
vite.config.ts
中引用插件
import { viteMockServe } from 'vite-plugin-mock'
export default defineConfig({
plugins: [
vue(),
viteMockServe({
supportTs: true,
mockPath: './src/mock'
})],
})
使用mock
新建文件src/mock/index.ts
,编写一下代码:
import { MockMethod } from 'vite-plugin-mock'
export default [
{
url: '/api/getNewsList',
method: 'get',
response: () => {
return {
code: 0,
message: 'success',
data: [
{
title: '标题111',
content: '内容1111'
},
{
title: '标题222',
content: '内容2222'
}
]
}
}
},
// more...
] as MockMethod[]
然后我们就可以在工程中进行 mock
数据的访问了,这里我们使用之前创建公共 api 请求方法 request。
<script>
import request from "@/utils/request.ts"
export default {
setup() {
request('/api/getNewsList').then(res => {
console.log(res);
// to do...
});
}
}
</script>