vue、java实现前后端分离(vue自定义端口号,加入element-ui,安装axios。自动生成java代码)

发布时间:2024年01月07日

一、自定义端口号

在已创建好的vue项目里打开vue.config.js,写入devServer:{? port:8088? },端口号可以自己定

在命令窗口启动一下vue项目,可以看到端口号已经改了

二、加入element-ui

在命令窗口执行? npm i element-ui

三、使用elemui-ui

在src中找到maiin.js,添加图中的代码,一二行是引入element-ui所需要的文件,

第三行是使用element-ui

四、安装axios

引用axios

五、创建java项目配置pom文件,并自动生成dept的代码(dept是mysql数据库的表)等

pom配置

<parent>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-parent</artifactId>
  <version>2.7.17</version>
</parent>

<groupId>com.aaa</groupId>
<artifactId>vueMp</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>

<name>vueMp</name>
<url>http://maven.apache.org</url>

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>3.8.1</version>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <version>2.7.17</version>
  </dependency>

  <!--连接数据库-->
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.47</version>
  </dependency>

  <!--mp-->
  <dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.5.3</version>
  </dependency>

  <!--自动生成代码-->
  <dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.5.3</version>
  </dependency>

  <!--模板-->
  <dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-engine-core</artifactId>
    <version>2.3</version>
  </dependency>

  <dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
  </dependency>

  <!--lombok-->
  <dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.6</version>
  </dependency>
</dependencies>

自动生成

public class MyTest {
    public static void main(String[] args) {
        //
        FastAutoGenerator.create("jdbc:mysql://localhost:3306/xm","root","root")
                                //根据自己idea写
                // 全局配置
                .globalConfig((scanner, builder) -> builder
                        .author("yh")
                            //yh无所谓
                        .outputDir("E:\\Code\\vueMp\\src\\main\\java")
                                //项目的java包路径
                )
                // 包配置
                .packageConfig(
                        (scanner, builder) ->
                                builder
                                        .parent("com.aaa")
                                        //生成代码的包下
                                        .pathInfo(Collections.singletonMap(OutputFile.xml, "E:\\Code\\vueMp\\src\\main\\resources\\mapper")))
//项目的java包路径下的resources\mapper(没有的话先创建好)
                // 策略配置
                .strategyConfig((scanner, builder) -> builder.addInclude(getTables(scanner.apply("请输入表名,多个英文逗号分隔?所有输入 all")))
                        .controllerBuilder().enableRestStyle().enableHyphenStyle()
                        .entityBuilder().enableLombok().addTableFills(
                                new Column("create_time", FieldFill.INSERT)
                        ).build())
                /*
                    模板引擎配置,默认 Velocity 可选模板引擎 Beetl 或 Freemarker
                   .templateEngine(new BeetlTemplateEngine())
                   .templateEngine(new FreemarkerTemplateEngine())
                 */
                .execute();


// 处理 all 情况

    }

    protected static List<String> getTables(String tables) {
        return "all".equals(tables) ? Collections.emptyList() : Arrays.asList(tables.split(","));
    }
}

然后运行出现提示all是全部的表,单独输入一个表就只生成一个表的代码

配置application.properties?

spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/xm?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=root
#  ??  ???    java.util
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
spring.jackson.time-zone=GMT+8
spring.jackson.serialization.write-date-keys-as-timestamps=false
#logging.level.com.baomidou.ant.test.dao=debug
#mybatis-plus my_name   myName
mybatis-plus.configuration.map-underscore-to-camel-case=true
# ??sql ??
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
#mybatis-plus.configuration.log-impl=
mybatis-plus.mapper-locations=classpath:/mapper/*.xml
#????   ???????0  ???1
mybatis-plus.global-config.db-config.logic-not-delete-value=0
mybatis-plus.global-config.db-config.logic-delete-value=1

添加cortroller层代码

调用service层去查部门的信息

@RestController
@CrossOrigin //主要用于跨域
@RequestMapping("/dept")
public class DeptController {
    @Resource
    private IDeptService deptService;

    @GetMapping
    public List<Dept> findAll(){
        List<Dept> list = deptService.list();
        return list;
    }
}

因为要实现前后端分离,所以手写一个config的跨域文件CrossConfig

@Configuration
public class CrossConfig {
    @Bean
    public CorsFilter corsFilter() {
        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        final CorsConfiguration corsConfiguration = new CorsConfiguration();
//        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.addAllowedHeader("*");  // 允许所有的头
        corsConfiguration.addAllowedOrigin("*");   //
        corsConfiguration.addAllowedMethod("*");  // * get  put delete head post
        source.registerCorsConfiguration("/**", corsConfiguration); // 所有的路由都能够进行跨域
        return new CorsFilter(source);
    }

}

写好启动类

@SpringBootApplication
@MapperScan("com.aaa.mapper")
public class App 
{
    public static void main( String[] args )
    {
        SpringApplication.run(App.class);
    }
}

在启动类里面执行后,浏览器打开http://localhost:8080/dept

六,有了数据后,实现用element-ui显示部门

写一个test的vue组件

<template>
  <el-table
    :data="tableData"
   
    :row-class-name="tableRowClassName">
    <el-table-column
      prop="id"
      label="编号">
    </el-table-column>
    <el-table-column
      prop="dname"
      label="部门名称"
     >
    </el-table-column>
    
  </el-table>
</template>

<style>
  .el-table .warning-row {
    background: oldlace;
  }

  .el-table .success-row {
    background: #f0f9eb;
  }
</style>

<script>
	
  export default {
    methods: {
      tableRowClassName({row, rowIndex}) {
        if (rowIndex%4 === 1) {
          return 'warning-row';
        } else if (rowIndex%4 === 3) {
          return 'success-row';
        }
        return '';
      }
    },
    data() {
      return {
        tableData: []
      }
    },
	created(){
		// vue   node 服务器  8899
		// axios  tomcat  8080
		// axios  发出请求
		// dept    http://localhost:8080/dept
	    this.$axios.get("dept").then(res=>{
			console.log(res.data);
			this.tableData=res.data;
		})
	}
  }
</script>

注册全局的axios

配置路由

http://localhost:8088/test

七、添加布局

在view下添加main文件main组件

<template>

  <el-container>
    <el-aside width="200px" style="background-color: rgb(238, 241, 246)">
      <!--  :router 按照路由规则进行跳转 -->
      <el-menu :default-openeds="['1', '3']" :router="true">
        <el-submenu index="1">
          <template slot="title"><i class="el-icon-message"></i>导航一</template>
          <el-menu-item-group>
            <template slot="title">分组一</template>
            <el-menu-item index="/test">选项1</el-menu-item>
            <el-menu-item index="/about">选项2</el-menu-item>
          </el-menu-item-group>
          <el-menu-item-group title="分组2">
            <el-menu-item index="1-3">选项3</el-menu-item>
          </el-menu-item-group>
          <el-submenu index="1-4">
            <template slot="title">选项4</template>
            <el-menu-item index="1-4-1">选项4-1</el-menu-item>
          </el-submenu>
        </el-submenu>
        <el-submenu index="2">
          <template slot="title"><i class="el-icon-menu"></i>导航二</template>
          <el-menu-item-group>
            <template slot="title">分组一</template>
            <el-menu-item index="2-1">选项1</el-menu-item>
            <el-menu-item index="2-2">选项2</el-menu-item>
          </el-menu-item-group>
          <el-menu-item-group title="分组2">
            <el-menu-item index="2-3">选项3</el-menu-item>
          </el-menu-item-group>
          <el-submenu index="2-4">
            <template slot="title">选项4</template>
            <el-menu-item index="2-4-1">选项4-1</el-menu-item>
          </el-submenu>
        </el-submenu>
        <el-submenu index="3">
          <template slot="title"><i class="el-icon-setting"></i>导航三</template>
          <el-menu-item-group>
            <template slot="title">分组一</template>
            <el-menu-item index="3-1">选项1</el-menu-item>
            <el-menu-item index="3-2">选项2</el-menu-item>
          </el-menu-item-group>
          <el-menu-item-group title="分组2">
            <el-menu-item index="3-3">选项3</el-menu-item>
          </el-menu-item-group>
          <el-submenu index="3-4">
            <template slot="title">选项4</template>
            <el-menu-item index="3-4-1">选项4-1</el-menu-item>
          </el-submenu>
        </el-submenu>
      </el-menu>
    </el-aside>
    <el-container>
      <el-header>Header</el-header>
      <el-main>
        <!--  存放组件的内容 -->
        <router-view></router-view>

      </el-main>
      <el-footer>Footer</el-footer>
    </el-container>
  </el-container>
</template>

<script>
</script>

<style>

.el-header, .el-footer {
  background-color: #B3C0D1;
  color: #333;
  text-align: center;
  line-height: 60px;
}

.el-aside {
  background-color: #D3DCE6;
  color: #333;
  text-align: center;
  line-height: 200px;
}

.el-main {
  background-color: #E9EEF3;
  color: #333;
  text-align: center;
  line-height: 20px;
}

body > .el-container {
  margin-bottom: 40px;
}

.el-container:nth-child(5) .el-aside,
.el-container:nth-child(6) .el-aside {
  line-height: 260px;
}

.el-container:nth-child(7) .el-aside {
  line-height: 320px;
}

.el-header {
  background-color: #B3C0D1;
  color: #333;
  line-height: 60px;
}

.el-aside {
  color: #333;
}
</style>

要注意

Main里面写一个容器

配置嵌套路由

http://localhost:8088/test 打开页面

当路由不存在的时候跳转到404 页面在路由文件里面写路由的规则

在views添加一个404的包,包里添加404页面

配置路由

再点开不存在页面就会跳转到这

八、实现简单登录跳转主页

创建login组件

<template>
  <div>
<el-form :model="ruleForm" status-icon  ref="ruleForm" label-width="100px" class="demo-ruleForm">
<el-form-item label="账号">
  <el-input type="text" v-model="ruleForm.username" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="密码" >
  <el-input type="password" v-model="ruleForm.password" autocomplete="off"></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>
</template>
<script>
export default {
  data() {
    return {
      ruleForm: {
        username: '',
        password: ''

      },

    };
  },
  methods: {
    submitForm(formName) {
      // 用户名  和密码
      // 如果成功
      // main
      // 路由   更改
      this.$router.push({name:'main'});
      //alert('submit!');
      // 跳转到 main页面


    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }

}
</script>

配置路由后,进入登录页面,登录后就会跳转至主页

http://localhost:8088/后就能到达登录页

文章来源:https://blog.csdn.net/weixin_47735032/article/details/135405935
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。