龙空技术网

java全栈CMS系统vue+element增删+正则校验3

一刀coder 662

前言:

此时看官们对“jsswal”大致比较关注,各位老铁们都想要学习一些“jsswal”的相关文章。那么小编同时在网络上汇集了一些关于“jsswal””的相关知识,希望我们能喜欢,姐妹们快快来了解一下吧!

1.新增前端elementUI静态页面构建AddModule

新增按钮

addmodule页面

gitee仓库地址:

addModule新增静态页面构建

<template>    <div class="addModule">        <div class="topNav">            <el-divider class="topLine"><i class="lineIcon el-icon-document-copy"></i><span                    class="lineTitle">新增模块</span></el-divider>        </div>        <div class="moduleSetNav">        </div>        <div class="addContent">            <router-view></router-view>            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm"                     :label-position="labelPosition">                <el-form-item label="模块名称" prop="name">                    <el-input class="inputLine" v-model="ruleForm.name"></el-input>                </el-form-item>                <el-form-item label="SEO标题" prop="seoTitle">                    <el-input class="inputLine" v-model="ruleForm.name"></el-input>                </el-form-item>                <el-form-item label="SEO关键字" prop="seoKeyword">                    <el-tag class="titleLeft"                            :key="tag"                            v-for="tag in dynamicTags"                            closable                            :disable-transitions="false"                            @close="handleClose(tag)">                        {{tag}}                    </el-tag>                    <el-input                            class="input-new-tag titleLeft"                            v-if="inputVisible"                            v-model="inputValue"                            ref="saveTagInput"                            size="small"                            @keyup.enter.native="handleInputConfirm"                            @blur="handleInputConfirm"                    >                    </el-input>                    <el-button v-else class="button-new-tag titleLeft" size="small" @click="showInput">+ 新增关键字                    </el-button>                </el-form-item>                <el-form-item label="SEO描述" prop="seo_description">                    <el-input class="textAreaWidth" type="textarea" v-model="ruleForm.name"></el-input>                </el-form-item>                <el-form-item class="" label="模块类型" prop="typeId">                    <el-cascader class="titleLeft"                                 v-model="value"                                 :options="options"                                 :props="{ expandTrigger: 'hover' }"                                 @change="handleChange"></el-cascader>                </el-form-item>                <el-form-item label="模块路径" prop="modulePath">                    <el-input class="inputLine" v-model="ruleForm.name"></el-input>                </el-form-item>                <el-form-item label="引用模板路径" prop="templatePath">                    <el-cascader class="titleLeft"                                 v-model="value"                                 :options="options"                                 :props="{ expandTrigger: 'hover' }"                                 @change="handleChange"></el-cascader>                </el-form-item>                <el-form-item label="引用页内模板路径" prop="subTemplatePath">                    <el-input class="inputLine" v-model="ruleForm.name"></el-input>                </el-form-item>                <el-form-item label="是否显示" prop="isNavShow">                    <el-switch class="titleLeft" v-model="ruleForm.delivery"></el-switch>                </el-form-item>                <el-form-item label="排序" prop="sort">                    <el-input class="inputLine" v-model="ruleForm.name"></el-input>                </el-form-item>                <el-form-item label="图片上传" prop="picList">                    <el-upload                            class="upload-demo titleLeft"                            ref="upload"                            action=";                            :on-preview="handlePreview"                            :on-remove="handleRemove"                            :file-list="fileList"                            :auto-upload="false">                        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>                        <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload">上传到服务器                        </el-button>                        <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>                    </el-upload>                </el-form-item>                <el-form-item label="模块内容" prop="moduleContent">                    <el-input class="textAreaWidth" type="textarea" v-model="ruleForm.name"></el-input>                </el-form-item>                <el-form-item>                    <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>                    <el-button @click="resetForm('ruleForm')">重置</el-button>                </el-form-item>            </el-form>        </div>    </div></template>
2.java后端:公共服务包server-util下生成UU-8位短ID

自增ID的缺陷:

(1)id连续,容易被探测

(2)需要+1次查询,才能得到id的值

(3)分布式存储中,id会出现重复

UUID:根据机器、时间等多个维度生成的32位16进制数,这里封装了8位短ID

package cevent.source.cloudcenter.server.util;/** * Created by Cevent on 2021/3/17. */import java.util.UUID;/** * @author cevent * @description 8位UUID * @date 2021/3/17 21:19 */public class UUID8Util {    /**     * 短ID是根据将32位ID,转为62进制8位ID,减少存储空间     * 原理是将UUID转为十进制,再对62取余,也可以再添加2个符号,转为64进制     */    public static String[] chars=new String[]{            //定义id使用的62个数字+字母            "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n",            "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z",            "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",            "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N",            "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"    };    /**     * 获取短UUID-short     */    public static String getShortUUID(){        StringBuffer shortBuffer=new StringBuffer();        String uuid=UUID8Util.getUUID();        for (int i=0;i<8;i++){            String str=uuid.substring(i*4,i*4+4);            int x=Integer.parseInt(str,16);            //对62取余            shortBuffer.append(chars[x%0x3E]);        }        return shortBuffer.toString();    }    /**     * 获取32位UUID     */    public static String getUUID(){        String uuid= UUID.randomUUID().toString();        //取消"-"符号        return uuid.replaceAll("-","");    }    //测试UUID转化    public static void main(String[] args) {        System.out.println(getShortUUID()); //XJH6Kt3h    }}
3.java后端:service层新增方法
//5.新增module,将传入的id转为module对象本身public void save(ModuleDto moduleDto){    //使用uu8位id    moduleDto.setUniId(UUID8Util.getShortUUID());    Module module=new Module();    BeanUtils.copyProperties(moduleDto,module);    moduleMapper.insert(module);}
4.java后端:business控制层实现
//5.新增,流方式需要加@RequestBody@RequestMapping("/save")public ModuleDto save(@RequestBody ModuleDto moduleDto){    LOG.info("传入的module DTO:{}",moduleDto);    moduleService.save(moduleDto);    return moduleDto;}
5.postman测试

http请求:{{source-cloudcenter}}/business/admin/module/save?uniId=88888&name=皮皮虾

postman测试结果

6.前端addModule新增请求--》后端save方法

前端-》后端请求逻辑

请求发送成功,数据回显

7.修改/删除module栏目功能开发(1)java后端:更新save方法(兼容insert、update)

//5.新增、修改module,将传入的id转为module对象本身public void save(ModuleDto moduleDto){    //复制dto    Module module= DuplicateUtil.copy(moduleDto,Module.class);    if(StringUtils.isEmpty(moduleDto.getUniId())){        this.insert(module);    }else{        this.update(module);    }}//向外暴露dto,不暴露实体类:插入数据private void insert(Module module){    module.setUniId(UUID8Util.getShortUUID());    if(module.getParentId()==null){        module.setParentId(0);    }    if(module.getTypeId()==null){        module.setTypeId(0);    }    try {        Date now =new Date();        String date=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(now);        long time=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date).getTime();        int timeInt=(int)(time/1000);        module.setCreateTime(now);        module.setUpdateTime(now);        module.setiCreateTime(timeInt);        module.setiUpdateTime(timeInt);    } catch (ParseException e) {        e.printStackTrace();    }    moduleMapper.insert(module);}//更新模块private void update(Module module){    moduleMapper.updateByPrimaryKey(module);}//删除模块public void delete(String uniId){    ModuleExample moduleExample=new ModuleExample();    moduleMapper.deleteByPrimaryKey(uniId);}
8.java后端:business-更新controller方法
//5.新增,流方式传参,加入@RequestBody@PostMapping("/save")public ResponseDataDto save(@RequestBody ModuleDto moduleDto){    LOG.info("传入的module DTO:{}",moduleDto);    ResponseDataDto responseData=new ResponseDataDto();    moduleService.save(moduleDto);    responseData.setResponseData(moduleDto);    return responseData;}/** 指定请求的格式为Delete * 6.删除模块,如果为多个参数,就定义多个/{param}/{param} */@DeleteMapping("/del/{uniId}")public ResponseDataDto del(@PathVariable String uniId){    LOG.info("传入的module uniId:{}",uniId);    ResponseDataDto responseData=new ResponseDataDto();    moduleService.delete(uniId);    return responseData;}
9.addModule更新title标题(传入module参数显示“更新模块”,未传入显示“新建模块”)

template绑定id

mounted挂载时更新当前title

10.module传参edit方法this.$router.push({name:"routerName",params:{父组件传到子组件的参数}})

父组件router传参

编辑时,通过slot-scope传参

11.引入sweetalert2轻提示

官网:

sweetalert

安装sweetalert2

asus@LAPTOP-CQRDCFKL MINGW64 /d/DEV_CODE/Intelligy_idead_code/spring/springcloud/yameng-cevent-source-cloudcenter/cevent-source-cloudcenter/cevent-ymcms-admin (master)

$ npm install sweetalert2 安装

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@2.3.2 (node_modules\fsevents):

npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@2.3.2: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\watchpack-chokidar2\node_modules\fsevents):

npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.13 (node_modules\webpack-dev-server\node_modules\fsevents):

npm WARN notsup SKIPPING OPTIONAL DEPENDENCY: Unsupported platform for fsevents@1.2.13: wanted {"os":"darwin","arch":"any"} (current: {"os":"win32","arch":"x64"})

+ sweetalert2@10.15.6

added 1 package from 7 contributors in 9.129s

64 packages are looking for funding

run `npm fund` for details

CDN引用 <script src="//cdn.jsdelivr.net/npm/sweetalert2@10"></script>

sweetalert2

router-index.js引入

router引入sweetalert

import Vue from "vue";import VueRouter from "vue-router";import ElementUI from "element-ui";import axios from "axios";import Swal from "sweetalert2";import Login from "../views/Login";//admin组件import Admin from "../views/Admin";import SiteData from "../views/main/SiteData";import Module from "../views/main/Module";import AddModule from "../views/main/module/AddModule";import ModuleInfo from "../views/main/module/ModuleInfo";import ModuleFile from "../views/main/module/ModuleFile";//公共组件import PageHelper from "../components/PageHelper";import "element-ui/lib/theme-chalk/index.css";Vue.use(VueRouter);Vue.use(ElementUI);//配置vue全局变量:任意组件--》this.$ajax可使用axiosVue.prototype.$axios=axios;Vue.prototype.$Swal=Swal;const routes = [    {        path: '/',        name: 'Login',        //component:Login,        /*        这里可使用redirect执行跳转        使用redirect区别,输入任意路径,路径名都会更改为         */        redirect: '/login'    }, {        path: '/login',        component: Login    }, {        path: '/',        name: 'admin',        component: Admin,        children: [            {   //子路由不以斜杠/开头路径                path: 'system/site/data',                name:'system/site/data',                component: SiteData,            },            {                path: 'business/module/set',                name:'business/module/set',                component: Module,            },            {                path: 'business/module/add',                name: 'business/module/add',                component: AddModule,                children:[                    {                        path:'info',                        name:'info',                        component:ModuleInfo,                    },                    {                        path:'file',                        name:'file',                        component:ModuleFile,                    },                ]            }        ]    },    {        path: '/pageHelper',        name: 'PageHelper',        component: PageHelper    }]const router = new VueRouter({    /*    后端数据请求模式:history    前端无请求模式#(难以请求后端数据):hash     */    mode: 'history',    //vue-router内置变量路径,指向public目录    base: process.env.BASE_URL,    routes})//抛出路由export default router;
module的del方法引人this.$Swal....

前端module中引入confirm提示框

sweetalert效果

sweetalert2实现删除confirm

实现修改module功能

12.前端正则校验:判断大小写字母、数字、空格,去空格换-横杠Template开启正则校验

template前端实现逻辑

Script的data中放入校验规则validate

validate正则校验实现逻辑

Data-return中锁定校验对象

return的rules锁定template中对象属性

Methods的方法在保存之前进行前端校验引用,这里的$refs引用在点击时传入的formName

save保存之前调用validate校验规则

前端校验效果

git仓库地址:

当前current提交

标签: #jsswal #vue elementui增删改查 #vue element 增删改查