手把手撸一个 Vue3 + Ts + ElementPlus 简易后台模板

您所在的位置:网站首页 断裂基因是什么 手把手撸一个 Vue3 + Ts + ElementPlus 简易后台模板

手把手撸一个 Vue3 + Ts + ElementPlus 简易后台模板

2024-07-13 15:58:23| 来源: 网络整理| 查看: 265

仓库地址在最后!

初始化项目

脚手架用的是vue-cli,vite还不太稳定,很多第三方库也存在兼容问题,为了能正常在实际项目中使用,还是选择了vue-cli。

如果不是最新的脚手架,就需要重新安装一下了:

npm install -g @vue/cli # OR yarn global add @vue/cli 复制代码

创建项目:

vue create vue3-ts-template // 选择Manually select features composition-api ([Vue 2] router, vuex, less, babel, eslint) Default ([Vue 2] babel, eslint) Default (Vue 3 Preview) ([Vue 3] babel, eslint) ✅ Manually select features 复制代码 Choose Vue version Babel TypeScript Progressive Web App (PWA) Support Router Vuex CSS Pre-processors Linter / Formatter Unit Testing E2E Testing

然后 Vue 选 3.0, css预处理器,看个人习惯,sass,less,stylus都可以。

创建完项目,把那些不需要的页面例如:helloword删了就行了,有一个shims-vue.d.ts 得留着。

安装 ElementPlus yarn add element-plus // main.ts import ElementPlus from 'element-plus'; import 'element-plus/lib/theme-chalk/index.css'; const app = createApp(App); app.use(ElementPlus); app.mount('#app'); 复制代码 登录页面

页面内容没什么好说的,想怎么画就怎么画。

登陆 复制代码

说说验证吧!ElementPlus 官方文档里面,还是按照Vue2.x的方式optionsApi写的:

但是我们既然采用了vue3,还是要紧跟时代步伐:

import { defineComponent, toRefs, reactive, ref } from 'vue'; import { useRouter } from 'vue-router'; interface UserForm { email: string; pass: string | number; } export default defineComponent({ setup () { const router = useRouter(); const state = reactive({ form: { email: 'admin', pass: 'admin123' } as UserForm, ruleForm: ref(null) }); const onSubmit = () => { // ruleForm.value.validate state.ruleForm.validate().then((valid: boolean) => { if (valid) { if (state.form.email === 'admin') { router.push({ path: '/' }); } } }); }; return { ...toRefs(state), onSubmit }; } }); 复制代码 绑定 ruleForm: ref(null) 声明ruleForm,并返回 state.ruleForm.validate() 而不是 state.ruleForm.value.validate() 布局

Footer 复制代码 刷新页面

布局全凭自己喜欢,我这里采用最简单,最常见的布局。这里做了一个刷新主要内容的功能。

setup() { const isRouterAlive = ref(true); const handleReload = () => { isRouterAlive.value = false; nextTick(() => { isRouterAlive.value = true; }); }; return {handleReload} } 复制代码 网页全屏 yarn add screenfull 复制代码 import screenfull, { Screenfull } from 'screenfull'; setup() { const change = () => { fullscreen.value = (screenfull as Screenfull).isFullscreen; }; // 全屏事件 const handleFullScreen = () => { if (!screenfull.isEnabled) { // 如果不允许进入全屏,发出不允许提示 ElMessage({ message: '暂不不支持全屏', type: 'warning' }); return false; } screenfull.toggle(); }; if (screenfull.isEnabled) { screenfull.on('change', change); } } 复制代码

要引入 Screenfull 这个接口,并做一下类型断言(screenfull as Screenfull),不这样ts编译通不过。

引入axios yarn add axios 复制代码 import axios, { AxiosResponse, AxiosRequestConfig } from 'axios'; import { ElMessage } from 'element-plus'; const instance = axios.create({ baseURL: process.env.VUE_APP_API_BASE_URL || '', timeout: 120 * 1000, withCredentials: true }); const err = (error) => { if (error.message.includes('timeout')) { // console.log('error---->',error.config) ElMessage({ message: '请求超时,请刷新网页重试', type: 'error' }); } if (error.response) { const data = error.response.data; const token = ''; if (error.response.status === 403) { ElMessage({ message: 'Forbidden', type: 'error' }); } if (error.response.status === 401 && !(data.result && data.result.isLogin)) { ElMessage({ message: 'Unauthorized', type: 'error' }); if (token) { // store.dispatch('Logout').then(() => { // setTimeout(() => { // window.location.reload(); // }, 1500); // }); } } } return Promise.reject(error); }; instance.interceptors.request.use((config: AxiosRequestConfig) => { return config; }, err); instance.interceptors.response.use((response: AxiosResponse) => { console.log(response); const config: AxiosRequestConfig = response.config || ''; const code = Number(response.data.status); if (code === 200) { if (config && config.successNotice) { ElMessage({ message: response.data.msg, type: 'success' }); } return response.data; } else { let errCode = [402, 403]; if (errCode.includes(response.data.code)) { ElMessage({ message: response.data.msg || '没有权限', type: 'warning' }); setTimeout(() => { window.location.reload(); }, 500); } } }, err); export default instance; 复制代码

这个axios二次封装就见仁见智了,看你们的业务和习惯,我只提供一个示例。

挂载到全局:

import axios from '@/utils/request'; app.config.globalProperties.$http = axios; // 使用 import { getCurrentInstance } from 'vue'; const { ctx } = getCurrentInstance() as any; ctx.$http(...).then(...) 复制代码

这里需要说明一点的是,如果引入AxiosResponse, AxiosRequestConfig这两个接口来做类型判断。要是在config中定义了一些额外的参数,又要使用就需要定义一个声明文件了。

我在config中定义了successNotice和errorNotice分别来判断请求成功和失败是否需要提示信息,并且它们都是非必填。

// shims.axios.d.ts import { AxiosRequestConfig } from 'axios'; declare module 'axios' { export interface AxiosRequestConfig { successNotice? : boolean, errorNotice? : boolean } } 复制代码 二次封装组件

为了更方便快捷的写业务,可以二次封装一些组件,简化操作。

Table 表格 {{item.label || '自定义header'}} {{scope.row[item.prop] || '需要自定义' }} import { defineComponent, PropType } from 'vue'; import HeroPaging from '../HeroPaging/index'; export default defineComponent({ components: { HeroPaging }, props: { // 数据 data: { type: Array, default: () => [] }, // 表格项 columns: { type: Array, default: () => [] }, // 绑定key rowKey: { type: String, default: 'id' }, // 分页信息 pagination: { type: Object, default: () => { return { page: 1, pageSize: 10, total: 100 }; } }, // 是否可选 allowSelect: { type: Boolean, default: false }, // 是否分页 showPaging: { type: Boolean, default: true } }, setup (props, { emit, slots, attrs }) { let multipleSelection = []; const handleSelectionChange = (val) => { multipleSelection = val; emit('select', multipleSelection); }; const handlePagingChange = (option) => { emit('pagingChange', option); }; return { handleSelectionChange, handlePagingChange }; } }); 复制代码

在一些常见的业务场景下,用起来就比较方便了:

日期 {{scope.data.date}}自定义slot 编辑 删除 const columns = [ { prop: 'date', label: '日期', fixed: true, width: 200, slot: { body: 'date', header: 'dateHeader' } }, { prop: 'name', label: '姓名', width: 200 }, { prop: 'address', label: '地址', width: 500 }, { prop: 'class', label: '班级', width: 200 }, { prop: 'school', label: '学校', width: 200 }, { prop: '', label: '操作', width: 110, slot: { body: 'action' }, fixed: 'right' } ]; 复制代码 Form 表单 {{op[item.selectLabel]}} {{op[item.selectLabel]}} import { computed, defineComponent, reactive, toRefs, ref, watch, watchEffect } from 'vue'; import HeroDatePicker from '@/components/HeroDatePicker/index'; export default defineComponent({ components: { HeroDatePicker }, props: { labelWidth: { type: String, default: '90px' }, formJson: { type: Array, default: () => [] }, modelValue: { type: Object, default: () => ({}) } }, setup (props, { emit }) { const formRef = ref(null); const state = reactive({ form: computed(() => props.modelValue) }); watch(() => state.form, (val) => { emit('update:modelValue', val); }, { deep: true }); const validate = () => { return new Promise((resolve, reject) => { formRef.value.validate().then((valid) => { resolve(valid); }).catch(err => { reject(err); }); }); }; return { ...toRefs(state), validate, formRef }; } }); 复制代码

提交 steup() { const formJson = [ { require: true, type: 'input', label: '姓名', placeholder: '请输入姓名', val: 'name', other: { style: 'width:220px' } }, { require: true, type: 'select', label: '年级', placeholder: '请选择年级', val: 'grade', selectLabel: 'label', selectVal: 'val', options: [{ val: 1, label: '一年级' }, { val: 2, label: '二年级' }] }, .... ] } 复制代码

这里需要提的一点是,自定义组件的v-model实现。

vue2的实现方式:

// ChildComponent.vue export default { model: { prop: 'title', event: 'change' }, props: { // 这将允许 `value` 属性用于其他用途 value: String, // 使用 `title` 代替 `value` 作为 model 的 prop title: { type: String, default: 'Default title' } } } 复制代码

vue3的实现方式:

// ChildComponent.vue export default { props: { modelValue: String // 以前是`value:String` }, methods: { changePageTitle(title) { this.$emit('update:modelValue', title) // 以前是 `this.$emit('input', title)` } } } 复制代码

更多具体介绍可前往官网。

DatePicker 时间选择器

DatePicker 为啥要封装一下?因为官方把value-format这个功能取消了(可以看看这个issues),所以每次都要自己去转化一次时间格式,太麻烦。

import { defineComponent, watch, reactive, toRefs } from 'vue'; import dayjs from 'dayjs'; export default defineComponent({ props: { type: { type: String, default: 'date' }, modelValue: { type: [String, Object, Array], default: '' }, valueFormat: { type: String, default: 'YYYY-MM-DD' } }, setup (props, { emit }) { const state = reactive({ value: props.modelValue || '' }); watch(() => state.value, (val) => { let formatVal = null; if (Array.isArray(val)) { formatVal = [dayjs(val[0]).format(props.valueFormat), dayjs(val[1]).format(props.valueFormat)]; } else { formatVal = dayjs(val).format(props.valueFormat); } console.log(formatVal); emit('update:modelValue', formatVal); }); return { ...toRefs(state) }; } }); 复制代码

elemment-plus 已经把moment换成了dayjs,我们不需要再安装就可以直接使用。

二次封装呀,我觉得有一点很重要,我们不可能把原来组件的所有props都穷举一遍,所以加上v-bind="$attrs"可以省很多事。

最后

这只是个简单的模板,可以用熟悉一下Vue3 和 Ts,要想在实际开发中使用,还是要慎重。

仓库地址:vue3_elementPlus_ts



【本文地址】

公司简介

联系我们

今日新闻


点击排行

实验室常用的仪器、试剂和
说到实验室常用到的东西,主要就分为仪器、试剂和耗
不用再找了,全球10大实验
01、赛默飞世尔科技(热电)Thermo Fisher Scientif
三代水柜的量产巅峰T-72坦
作者:寞寒最近,西边闹腾挺大,本来小寞以为忙完这
通风柜跟实验室通风系统有
说到通风柜跟实验室通风,不少人都纠结二者到底是不
集消毒杀菌、烘干收纳为一
厨房是家里细菌较多的地方,潮湿的环境、没有完全密
实验室设备之全钢实验台如
全钢实验台是实验室家具中较为重要的家具之一,很多

推荐新闻


图片新闻

实验室药品柜的特性有哪些
实验室药品柜是实验室家具的重要组成部分之一,主要
小学科学实验中有哪些教学
计算机 计算器 一般 打孔器 打气筒 仪器车 显微镜
实验室各种仪器原理动图讲
1.紫外分光光谱UV分析原理:吸收紫外光能量,引起分
高中化学常见仪器及实验装
1、可加热仪器:2、计量仪器:(1)仪器A的名称:量
微生物操作主要设备和器具
今天盘点一下微生物操作主要设备和器具,别嫌我啰嗦
浅谈通风柜使用基本常识
 众所周知,通风柜功能中最主要的就是排气功能。在

专题文章

    CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭