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>
vite+ts+vue3+router4+Pinia+ElmPlus+axios+mock项目基本配置的更多相关文章
- 基于 vite 创建 vue3 全家桶项目(vite + vue3 + tsx + pinia)
		vite 最近非常火,它是 vue 作者尤大神发布前端构建工具,底层基于 Rollup,无论是启动速度还是热加载速度都非常快.vite 随 vue3 正式版一起发布,刚开始的时候与 vue 绑定在一起 ... 
- vue3.0+vite+ts项目搭建--基础配置(二)
		集成vue-router 使用yarn yarn add vue-router@next --save 安装完成之后在src目录下创建文件夹router/index.ts,创建完成之后需要在Vue-R ... 
- vite创建vue3+ts项目流程
		vite+vue3+typescript搭建项目过程 vite和vue3.0都出来一段时间了,尝试一下搭vite+vue3+ts的项目 相关资料网址 vue3.0官网:https://v3.vue ... 
- Vite+TS带你搭建一个属于自己的Vue3组件库
		theme: nico 前言 随着前端技术的发展,业界涌现出了许多的UI组件库.例如我们熟知的ElementUI,Vant,AntDesign等等.但是作为一个前端开发者,你知道一个UI组件库是如何被 ... 
- vue3.0+vite+ts项目搭建--初始化项目(一)
		vite 初始化项目 使用npm npm init vite@latest 使用yarn yarn create vite 使用pnpm pnpx create-vite 根据提示输入项目名称,选择v ... 
- vue3中pinia的使用总结
		pinia的简介和优势: Pinia是Vue生态里Vuex的代替者,一个全新Vue的状态管理库.在Vue3成为正式版以后,尤雨溪强势推荐的项目就是Pinia.那先来看看Pinia比Vuex好的地方,也 ... 
- Vue CLI 5 和 vite 创建 vue3.x 项目以及 Vue CLI 和 vite 的区别
		这几天进入 Vue CLI 官网,发现不能选择 Vue CLI 的版本,也就是说查不到 vue-cli 4 以下版本的文档. 如果此时电脑上安装了 Vue CLI,那么旧版安装的 vue 项目很可能会 ... 
- vue3 vite2 封装 SVG 图标组件 - 基于 vite 创建 vue3 全家桶项目续篇
		在<基于 vite 创建 vue3 全家桶>一文整合了 Element Plus,并将 Element Plus 中提供的图标进行全局注册,这样可以很方便的延续 Element UI 的风 ... 
- vue3 学习笔记 (二)——axios 的使用有变化吗?
		本篇文章主要目的就是想告诉我身边,正在学 vue3 或者 准备学 vue3 的同学,vue3中网络请求axios该如何使用,防止接触了一点点 vue3 的同学会有个疑问?生命周期.router .vu ... 
- 【建议收藏】缺少 Vue3 和 Spring Boot 的实战项目经验?我这儿有啊!
		缺少 Vue3 和 Spring Boot 的实战项目经验?缺少学习项目和练手项目?我这儿有啊! 从 2019 年到 2021 年,空闲时间里陆陆续续做了一些开源项目,推荐给大家啊!记得点赞和收藏噢! ... 
随机推荐
- C++面向对象编程之成员模板、模板特化、偏特化和模板模板参数
			1.成员模板 理解起来就是类是模板类,他里面的成员函数又是个模板函数 上图例子:用派生类构造父类 2.模板特化 就是在类模板泛化后写特化的类,在template<>里不绑定类型,而在类后面 ... 
- springmvc 上传文件时的错误
			使用springmvc上传文件一直失败,文件参数一直为null, 原来是配置文件没写成功. <bean id="multipartResolver" class=" ... 
- Go 互斥锁Mutex
			Mutex是一个互斥锁,可以创建为其他结构体的字段:零值为解锁状态.Mutex类型的锁和线程无关,可以由不同的线程加锁和解锁.互斥锁的作用是保证共享资源同一时刻只能被一个 Goroutine 占用,一 ... 
- Android自动化测试工具调研
			原文地址:Android自动化测试工具调研 - Stars-One的杂货小窝 Android测试按测试方式分类,可分为两种:一种是传统逻辑单元测试(Junit),另外一种则是UI交互页面测试. 这里详 ... 
- 小程序返回上一级页面背景音乐报错 setBackgroundAudioState:fail title is nil!;
			小程序初始化在onLoad的时候加载了一次背景音乐. 如果此时报错是title必传.如果没有 会报错一次 setBackgroundAudioState:fail title is nil!; 这个都 ... 
- sql语法巧用之not取反
			数据库的重要性和通用性都不用说了,什么sql的通用性,sql优化之类的也不必说了,咱们今天来聊聊另一个有意思的话题:如何取一个筛选的反面案例. 1. 举几个正反案例的例子 为了让大家理解我们的假设场景 ... 
- python读取文本数据某一列
			import codecs f = codecs.open('test1 - 副本.txt', mode='r', encoding='utf-8') # 打开txt文件,以'utf-8'编码读取 l ... 
- 空链接的作用以及<a href="#"></a>和<a href="javascript:;"></a>的区别
			空链接的作用以及<a href="#"></a>和<a href="javascript:;"></a>的区别在 ... 
- 永久解决Ubuntu下adb权限问题
			在Linux环境下使用adb链接手机,经常会遇到全下问题,如下: adb: unable to connect for root: insufficient permissions for devic ... 
- SSH(四)控制层、业务层、dao层类的创建以及applicationcontext.xml和struts.xml配置
			ssh框架的运作方式就是页面请求控制层,控制层调用dao层的方法,dao层完成对数据的操作的一个过程. 现在我们初步简单编写各层的class. action控制层: ActionSupport:实现了 ... 
