5、用户添加功能(3)

预备知识(备查):
1)element-ui使用手册
2)springboot+jpa
3 ) axios
4)moment中文站

目标

本章制作前后端分离的项目,前后端实现跨域访问

  • 注册功能开发

项目位置

前台vue:d:\vue\springboot-vue
后台spring-boot:D:\springboot\demo-jpa1

框架选择

前端框架选择element-ui
跨域请求选择axios

第一步:新建工程springboot-vue,并导入常用的包

1.1 d:\vue进入命令行状态,输入以下命令

vue init webpack springboot-vue

1.2 进入d:\vue\springboot-vue目录,输入以入命令

cnpm install 
cnpm install vue-router vue-resource --save
cnpm install element-ui -S
cnpm install axios --save
cnpm install --save vue-axios
cnpm install qs

1.3 确认是否安装成功(axios同理)
查看配置文件package.json,是否有element-ui组件的版本号 如下图:

在node_modules中可以看到 element-ui的文件夹 ,所有安装的源文件可以在这里面找到

第二步 编码

参考官网:https://element.eleme.cn/#/zh-CN/component/quickstart

在main.js文件中引入 element 组件

以下步骤皆可查看element手册

step 1 引入

引入方式有两种 1)完整引入 2)按需引入 初学者可以选择完整引入,以后熟练了再按需引入
完整引入
在 main.js 中写入以下内容:

import Vue from 'vue';
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import App from './App.vue';

Vue.use(ElementUI);

new Vue({
  el: '#app',
  render: h => h(App)
});

注意,如有与原有引入重复的,要出重复。比如vue,app就不需要重复引入

国际化(了解)

Element 组件内部默认使用中文,若希望使用其他语言,则需要进行多语言设置。以英文为例,在 main.js 中:

import lang from 'element-ui/lib/locale/lang/en'
import locale from 'element-ui/lib/locale'
// 设置语言
locale.use(lang)

经过上述两步,完成了element-ui的引入
axios引入略,直接上main.js完整代码

第三步:前台工程编码vue:d:\vue\springboot-vue

1)main.js完整的代码如下

import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
//import lang from 'element-ui/lib/locale/lang/en'
//import locale from 'element-ui/lib/locale'
//以下4行引入axios
import axios from 'axios'
import VueAxios from 'vue-axios'
axios.defaults.withCredentials = false//这个默认即为false,如果改为true,可以传递session信息,后端要做相应修改来放行,
Vue.prototype.$axios = axios;   //在vue中使用axios
// 设置语言
//locale.use(lang)
Vue.use(ElementUI);
Vue.config.productionTip = false

new Vue({
  el: '#app',
    router,
  render: h => h(App)
});

引用qs

import qs from 'qs';
Vue.prototype.$qs = qs;

2)编写注册页面Register.vue

https://element.eleme.cn/#/zh-CN/component/form
页面里找到如下表单,

image.png

在src目录下新建reg目录
后在目录下新建Register.vue文件
拷贝element-ui对应页面的内容到Register.vue里
如图:


image.png

3)路由文件router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import ElMain from '@/components/ElMain'
Vue.use(Router)

        export default new Router({
        routes: [
            {
                path: '/',
                name: 'HelloWorld',
                component: HelloWorld
            },
            {
                path: '/reg',
                name: 'Register',
                component: Register
            }
        ]
    })

启动并测试:

  npm run dev
  http://localhost:8081/#/reg
image.png

继续完成界面开发

    <template>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item label="用户名" prop="userName">
        <el-input v-model="ruleForm.userName"></el-input>
      </el-form-item>
       <el-form-item label="密码" prop="password">
        <el-input v-model="ruleForm.password"></el-input>
      </el-form-item>
       <el-form-item label="真实姓名" prop="realName">
        <el-input v-model="ruleForm.realName"></el-input>
      </el-form-item>
      <el-form-item label="用户类别" prop="useType">
        <el-select v-model="ruleForm.useType" placeholder="请选择用户类别">
          <el-option label="医院管理员" value="1"></el-option>
          <el-option label="挂号收费员" value="2"></el-option>
          <el-option label="门诊医生" value="3"></el-option>
          <el-option label="医技医生" value="4"></el-option>
          <el-option label="药房操作员" value="5"></el-option>
          <el-option label="财务管理员" value="6"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="医生职称" prop="docTitleid">
        <el-select v-model="ruleForm.docTitleid" placeholder="请选择医生职称">
          <el-option 
          v-for="item in constantItems"
          :key="item.id" 
          :label="item.constantName" 
          :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      
     <el-form-item label="是否参与排班" prop="isScheduling">
        <el-switch v-model="ruleForm.isScheduling"></el-switch>
      </el-form-item>
      
       <el-form-item label="所在科室" prop="deptId">
        <el-select v-model="ruleForm.deptId" placeholder="请选择所在科室">
          <el-option 
          v-for="item in depts"
          :key="item.id" 
          :label="item.deptName" 
          :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
       <el-form-item label="挂号级别" prop="registLeid">
        <el-select v-model="ruleForm.registLeid" placeholder="请选择挂号级别">
          <el-option 
          v-for="item in RegistLevels"
          :key="item.id" 
          :label="item.registName" 
          :value="item.id">
          </el-option>
        </el-select>
      </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>
    </template>

    <script>
        export default {
        data() {
          return {
              //这里的属性跟实体类里的相同
            ruleForm: {
              userName: '',
              password: '',
              realName: '',
              //下拉列表
              useType: '',
              docTitleid: '',
              isScheduling:false,
              deptId:'',
              registLeid:'',
              delMark: '1'
            },
            constantItems:[{"id":'11',"constantName":'内科'},{"id":'12',"constantName":'儿科'}],
            depts:[{"id":'11',"deptName":'神经内科'},{"id":'2',"deptName":'普通内科'}],
            RegistLevels:[{"id":'1',"registName":'专家号'},{"id":'2',"registName":'普通号'}],
            rules: {
              userName: [
                { required: true, message: '请输入用户名称', trigger: 'blur' },
                { min: 3, max: 64, message: '长度在 3 到64 个字符', trigger: 'blur' }
              ],
              password: [
                { required: true, message: '请输入密码', trigger: 'blur' },
                { min: 6, max: 64, message: '长度在 6 到 64 个字符', trigger: 'blur' }
              ],
              realName: [
                { required: true, message: '请输入真实姓名', trigger: 'blur' },
                { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
              ]
            }
          };
        },
        methods: {
          submitForm(formName) {
            this.$refs[formName].validate((valid) => {
              if (valid) {
                alert('submit!');
                
              } else {
                console.log('error submit!!');
                return false;
              }
            });
          },
          resetForm(formName) {
            this.$refs[formName].resetFields();
          }
        }
      }
    </script>
    <style>
    </style>

第四步:后台spring-boot:D:\springboot\demo-jpa1

1)主配置文件中增加跨域权限配置SpringConfig.java内容如下

package com.neuedu.demo.config;
import static org.springframework.web.cors.CorsConfiguration.ALL;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@ComponentScan(basePackages={"com.neuedu.demo"})
public class SpringConfig {
    //增加跨域权限配置
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                // 限制了路径和域名的访问
                /*registry.addMapping("/api*").allowedOrigins("http://localhost:8081");*/
                registry.addMapping("/**")
                //授权访问的前端地址
                .allowedOrigins("http://localhost:8081")
                //设置允许访访问 的方法
                .allowedMethods(ALL)
                //设置允许的header
                .allowedHeaders(ALL)
                 //是否允许证书
                .allowCredentials(true);
            }
        };
    }
}

springboot2.2.6跨域

    @SpringBootConfiguration
    @ComponentScan(basePackages={"com.neuedu.his"})
    public class SpringConfig {
    //xml:<bean id="" class="org.springframework.web.servlet.config.annotation.WebMvcConfigurer"/>
        @Bean
        public WebMvcConfigurer corsConfigurer() {
            //WebMvcConfigurerAdapter  implements WebMvcConfigurer  --->addCorsMappings
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    // 限制了路径和域名的访问
                    registry.addMapping("/**")
                    //授权访问的前端地址
                    .allowedOrigins("http://localhost:8080")
                    //设置允许访访问 的方法
                    .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
                    //设置允许的header
                    .allowedHeaders("*")
                     //是否允许证书
                    .allowCredentials(true);
                }
            };
        }
    }

application.properties 下增加如下设置

spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

HisUser实体类

package com.neuedu.demo.domain;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name = "user")
@GenericGenerator(name = "jpa-uuid", strategy = "uuid")
public class HisUser implements Serializable{
    @Id
    @GeneratedValue(generator = "jpa-uuid")
    @Column(length = 32)
    private String id;
    @Column(name = "userName", nullable = true, length = 64)
    private String userName;
    @Column(name = "password", nullable = true, length = 64)
    private String password;
    @Column(name = "realName", nullable = true, length = 64)
    private String realName;
    @Column(name = "useType", nullable = true, length = 1)
    private int useType;
    @Column(name = "docTitleid", nullable = true, length = 9)
    private int docTitleid;
    @Column(name = "isScheduling", nullable = true, length = 6)
    private String isScheduling;
    @Column(name = "deptId", nullable = true, length = 9)
    private String deptId;
    @Column(name = "registLeid", nullable = true, length = 9)
    private String registLeid;
    @Column(name = "delMark", nullable = true, length = 1)
    private String delMark;

......get/set略
}

2)HisUserController

package com.neuedu.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.neuedu.demo.dao.HisUserRepository;
import com.neuedu.demo.domain.HisUser;

@RestController
@RequestMapping(value = "/reg")
public class HisUserController {
    @Autowired
    private HisUserRepository hisUserRepository;

    @RequestMapping(path = "add")
    public String add(@RequestBody HisUser user) {
        System.out.println("用户注册准备");
        System.out.println(user.getIsScheduling());
        hisUserRepository.save(user);
        return "success";
    }
}

页面添加axios请求

改造methods部分

        methods: {
          submitForm(formName) {
            this.$refs[formName].validate((valid) => {
              if (valid) {
                //alert('submit!');
//此处为新增加代码,用于请求后台进行注册               this.$axios.post('http://localhost:8082/reg/add',this.ruleForm, {
                            headers: {
                                'Content-Type': 'application/json;charset=UTF-8'
                            }})
                .then(response=>{
                    alert(response.data);
                })
              } else {
                console.log('error submit!!');
                return false;
              }
            });
          },
          resetForm(formName) {
            this.$refs[formName].resetFields();
          }
        }

测试

npm run dev

启动服务,浏览器输入
http://localhost:8081/

image.png

点击save按钮,显示成功

image.png

日期控件的使用方式

^ - ^
利用日期控件自带的方法 value-format

https://element.eleme.cn/#/zh-CN/component/date-picker#ri-qi-ge-shi

        <el-date-picker type="date" placeholder="选择日期" v-model="form.birthday" style="width: 100%;"  value-format="yyyy-MM-dd"  format="yyyy年MM月dd日"></el-date-picker>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,509评论 6 504
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,806评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,875评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,441评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,488评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,365评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,190评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,062评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,500评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,706评论 3 335
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,834评论 1 347
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,559评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,167评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,779评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,912评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,958评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,779评论 2 354

推荐阅读更多精彩内容

  • 预备知识(备查):1)element-ui使用手册2)vue+servlet3 ) axios 建表语句 目标 本...
    wqjcarnation阅读 1,531评论 1 11
  • 基于Vue的一些资料 内容 UI组件 开发框架 实用库 服务端 辅助工具 应用实例 Demo示例 element★...
    尝了又尝阅读 1,151评论 0 1
  • 一、技术准备 二、开发工具 三、使用 vue-cli 快速开始模板项目 四、给项目添加组件 五、使用vue-rou...
    35eeabfa0772阅读 31,539评论 4 60
  • 响应式布局的理解 响应式开发目的是一套代码可以在多种终端运行,适应不同屏幕的大小,其原理是运用媒体查询,在不同屏幕...
    懒猫_6500阅读 787评论 0 0
  • vue-cli搭建项目 确保安装了node与npm 再目标文件夹下打开终端 执行cnpm i vue-cli -g...
    Akiko_秋子阅读 3,238评论 1 22