vue+ssm实现登录页面和部门管理

导读:本篇文章讲解 vue+ssm实现登录页面和部门管理,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

创建数据库/表:

创建数据库:

create database 0927_ssm_vue_db #创建数据库
default character set utf8mb4 #设置字符集
default collate utf8mb4_general_ci #设置排序规则

创建数据表:

#创建部门
CREATE TABLE tb_dept
(
	dept_id int PRIMARY KEY auto_increment,
	dept_name VARCHAR(20)
)

select * from tb_dept

INSERT INTO tb_dept
(dept_name)
select '人事部' UNION
select '财务部' UNION
select 'IT部' 

CREATE TABLE tb_emp
(
	emp_id INT PRIMARY KEY auto_increment,
	emp_name varchar(20),
	sex char(1),
	birthday date,
	phone varchar(11),
	dept_d int #所属部门
)

select * from tb_emp

insert into tb_emp
VALUES
(null,'张三','男','2000-01-10','13112345678',1),
(null,'李四','女','2002-11-12','13112345679',2)

在这里插入图片描述

ssm框架—后台搭建:

项目整体框架:

在这里插入图片描述

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>org.example</groupId>
  <artifactId>0927_ssm_vue_KTLX</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>0927_ssm_vue_KTLX Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <maven.compiler.source>8</maven.compiler.source>
    <maven.compiler.target>8</maven.compiler.target>
    <servlet.version>4.0.1</servlet.version>
    <jsp.version>2.2</jsp.version>
    <jstl.version>1.2</jstl.version>
    <spring.version>5.3.14</spring.version>
    <commons-dbcp.version>1.4</commons-dbcp.version>
    <mybatis.version>3.4.6</mybatis.version>
    <mybatis-spring.version>1.3.3</mybatis-spring.version>
    <mysql-connector-java.version>8.0.11</mysql-connector-java.version>
    <fastjson.version>1.2.78</fastjson.version>
  </properties>
  <dependencies>
    <!-- 添加javaEE支持 -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>${servlet.version}</version>
      <!-- provided只在编译时支持,发布时不拷贝文件 -->
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>${jsp.version}</version>
      <!-- provided只在编译时支持,发布时不拷贝文件 -->
      <scope>provided</scope>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>${jstl.version}</version>
    </dependency>
    <!--引入spring基础模块-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- dbcp连接池 -->
    <dependency>
      <groupId>commons-dbcp</groupId>
      <artifactId>commons-dbcp</artifactId>
      <version>${commons-dbcp.version}</version>
    </dependency>
    <!-- mybatis -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <!-- mybatis spring整合 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>${mybatis-spring.version}</version>
    </dependency>
    <!--mybatis插件PageHelper-->
    <dependency>
      <groupId>com.github.pagehelper</groupId>
      <artifactId>pagehelper</artifactId>
      <version>5.1.0</version>
    </dependency>
    <dependency>
      <groupId>com.github.abel533</groupId>
      <artifactId>mapper</artifactId>
      <version>3.0.1</version>
    </dependency>
    <!-- mysql驱动类 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql-connector-java.version}</version>
    </dependency>
    <!--fastjson处理json数据-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>${fastjson.version}</version>
    </dependency>
    <!--lombok 简化实体内容-->
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.24</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.13.2.2</version>
    </dependency>
    <!--logback记录文件日志-->
    <dependency>
      <groupId>org.logback-extensions</groupId>
      <artifactId>logback-ext-spring</artifactId>
      <version>0.1.4</version>
    </dependency>
    <!--数据校验-->
    <dependency>
      <groupId>javax.validation</groupId>
      <artifactId>validation-api</artifactId>
      <version>2.0.1.Final</version>
    </dependency>
    <dependency>
      <groupId>org.hibernate</groupId>
      <artifactId>hibernate-validator</artifactId>
      <version>6.1.0.Final</version>
    </dependency>

    <!--文件生成-->
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi</artifactId>
      <version>3.17</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml</artifactId>
      <version>3.17</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.poi/poi-ooxml-schemas -->
    <dependency>
      <groupId>org.apache.poi</groupId>
      <artifactId>poi-ooxml-schemas</artifactId>
      <version>3.17</version>
    </dependency>
    <!--发送邮件-->
    <dependency>
      <groupId>com.sun.mail</groupId>
      <artifactId>jakarta.mail</artifactId>
      <version>1.6.7</version>
    </dependency>
  </dependencies>


</project>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

  <!--定义spring的配置文件,用于在spring监听器监听网站启动的时候,创建spring容器-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring-mybatis.xml</param-value>
  </context-param>
  <!--配置spring监听器,用于创建spring容器-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <context-param>
    <param-name>logbackConfigLocation</param-name>
    <!--logback.xml放在resources/config路径下-->
    <param-value>classpath:logback.xml</param-value>
  </context-param>
  <listener>
    <listener-class>ch.qos.logback.ext.spring.web.LogbackConfigListener</listener-class>
  </listener>

  <!--配置跨域过滤器-->
  <!-- 跨域请求 -->
  <filter>
    <filter-name>SimpleCORSFilter</filter-name>
    <filter-class>com.aaa.demo.filter.SimpleCORSFilter</filter-class>
    <init-param>
      <param-name>IsCross</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>SimpleCORSFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!--配置spring的编码过滤器-->
  <filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


  <!--配置springMVC前端控制器-->
  <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <!--springMVC需要配置相关的组件(处理器映射器,适配器。。。)
         因此我们要自己定义配置文件,在配置文件中定义这些组件。
         如果自己没有定义这个配置文件,springMVC的前端控制器默认加载 servlet名字+servlet.xml这个文件
         找不到则报错。
         一般情况下,我们要自己在init-param中配置这个文件,param-name固定是contextConfigLocation
      -->
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring-mvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <!--凡是以.do结尾的请求都让springMVC来处理
    <url-pattern>*.do</url-pattern>
    -->
    <!-- 斜杠配置(/):表示所有的默认请求都交给DisaptherServlet来处理
                     导致的问题就是请求静态资源的时候无法处理
    -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

db.properties:

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/0927_ssm_vue_db?useSSL=false&serverTimezone=UTC&characterEncoding=utf8&allowPublicKeyRetrieval=true
jdbc.username=root
jdbc.password=123456

logback.xml:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
     <!-- Where are log files
          LOG_HOME: ./  表示日志生成的文件创建在当前项目所在磁盘的根目录下
     -->
    <property name="LOG_HOME" value="./" />
    <!-- Console log output -->
    <appender name="Console" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <!-- 格式化输出:%d:表示日期 %thread:表示线程名 %-5level:级别从左显示5个字符宽度-->
            <pattern>%d{HH:mm:ss.SSS} [%thread] > %green(%-5level) %cyan(%logger{35}) - %m%n</pattern>
        </encoder>
    </appender>

    <!-- Log file debug output -->
    <appender name="File" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
			<!--
            <fileNamePattern>D:/logs/%d{yyyy-MM-dd}.log.zip</fileNamePattern>
			-->
			<fileNamePattern>/aaalogs/%d{yyyy-MM-dd}.aaa.log.zip</fileNamePattern>
            <!--日志最大保存时间-->
            <maxHistory>365</maxHistory>
        </rollingPolicy>
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} > %-5level %X{X-B3-TraceId:-} ${springAppName:-} %logger{35} %m%n</pattern>
        </encoder>
    </appender>
    <!--debug:级别最高级别 开发
        info: 信息
        error:错误级别 项目上线
    -->
    <root level="info">
        <appender-ref ref="Console"/>
        <appender-ref ref="File"/>
    </root>
</configuration>

mybatis-config.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!-- 配置日志工具 -->
        <setting name="logImpl" value="SLF4J"/>
        <!--配置将下划线字段转为小驼峰-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!--配置分页插件和通用Mapper插件-->
    <plugins>
        <!--拦截器-->
        <plugin interceptor="com.github.pagehelper.PageInterceptor">

            <property name="offsetAsPageNum" value="true"/>
            <!--配置数据库方言 4.0版本以后不用写-->
            <!--<property name="helperDialect" value="mysql"/>-->
            <!--是否做count查询-->
            <property name="rowBoundsWithCount" value="true"/>
            <!--合理化分页-->
            <property name="reasonable" value="true"/>
        </plugin>
        <plugin interceptor="com.github.abel533.mapperhelper.MapperInterceptor">
            <!--主键自增回写方法,默认值MYSQL -->
            <!--<property name="IDENTITY" value="MYSQL" />-->
            <!--通用Mapper默认接口,我们定义的Mapper需要实现该接口 -->
            <property name="mappers" value="com.github.abel533.mapper.Mapper" />
        </plugin>
    </plugins>
</configuration>

spring-mvc.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--扫描controller包,管理其中定义的controller类-->
    <context:component-scan base-package="com.aaa.demo.controller"/>
    <!--启用注解方式配置 springMVC请求使用的相关组件
        处理器映射器,处理器适配器,处理器(Controller...其他注解)
    -->
    <mvc:annotation-driven/>

    <!--配置拦截器集合-->
<!--    <mvc:interceptors>-->
<!--        &lt;!&ndash;配置一个具体的拦截器&ndash;&gt;-->
<!--        <mvc:interceptor>-->
<!--            &lt;!&ndash;配置要拦截的请求地址&ndash;&gt;-->
<!--            <mvc:mapping path="/**"/>-->
<!--            &lt;!&ndash;配置要放行的请求&ndash;&gt;-->
<!--            <mvc:exclude-mapping path="/index.jsp"/>-->
<!--            <mvc:exclude-mapping path="/forward/toLogin"/>-->
<!--            <mvc:exclude-mapping path="/emp/login"/>-->
<!--            &lt;!&ndash;放行静态资源&ndash;&gt;-->
<!--            <mvc:exclude-mapping path="/assets/**"/>-->
<!--            <mvc:exclude-mapping path="/assets/img/*.jpeg"/>-->
<!--            &lt;!&ndash;配置拦截器类&ndash;&gt;-->
<!--            <bean class="com.aaa.hr.interceptor.LoginCheckInterceptor"/>-->
<!--        </mvc:interceptor>-->

<!--    </mvc:interceptors>-->

    <!--配置DefaultServlet处理其他请求(静态资源)-->
    <mvc:default-servlet-handler/>

</beans>

spring-mybatis.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--配置spring扫描包-->
    <context:component-scan base-package="com.aaa.demo.service"/>

    <!--通过spring配置数据库的连接属性文件-->
    <context:property-placeholder location="classpath:db.properties"/>
    <!--通过spring来配置数据库连接池的数据源对象-->
    <bean id="ds" class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <!--配置连接池数据源需要使用四大金刚(数据库连接属性)-->
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--通过spring来配置mybatis的会话工厂和其他相关配置
        原来的时候,mybatis的会话工厂由程序员来创建,现在通过spring来创建管理
        这个就体现了Spring的IoC特征(控制反转)
    -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--配置SqlSession依赖的数据源对象-->
        <property name="dataSource" ref="ds"/>
        <!--配置mybatis要使用的类型别名定义-->
        <property name="typeAliasesPackage" value="com.aaa.demo.entity"/>
        <!--配置mybatis的主配置文件的路径,spring会自动加载mybatis的配置文件-->
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
        <!--配置mybatis的Mapper文件的路径:spring中Mapper接口和Mapper文件路径可以由区别-->
        <property name="mapperLocations" value="classpath:com/mapper/*.xml"/>

    </bean>
    <!--通过spring来配置Mybatis的Mapper接口
        通过包扫描的方式进行配置
    -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--配置Mybatis的Mapper接口-->
        <property name="basePackage" value="com.aaa.demo.mapper"/>
        <!--配置可以创建Mapper接口对象的SqlSession使用的SqlSessionFactory对象的名字-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>

</beans>

Dept:

package com.aaa.demo.entity;

import lombok.Data;

@Data
public class Dept {
    private Integer deptId;
    private String deptName;
}

DeptMapper :

package com.aaa.demo.mapper;

import com.aaa.demo.entity.Dept;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface DeptMapper {
    @Select("select dept_id,dept_name from tb_dept")
    List<Dept> listAll();

    @Insert("insert into tb_dept values (null,#{deptName})")
    int insert(Dept dept);
}

在这里插入图片描述

DeptMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.aaa.demo.mapper.DeptMapper">

</mapper>


DeptServiceImpl :

package com.aaa.demo.service.impl;

import com.aaa.demo.entity.Dept;
import com.aaa.demo.mapper.DeptMapper;
import com.aaa.demo.service.IDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DeptServiceImpl implements IDeptService {
    @Autowired
    private DeptMapper deptMapper;

    @Override
    public List<Dept> listAll() {
        return deptMapper.listAll();
    }

    @Override
    public int add(Dept dept) {
        return deptMapper.insert(dept);
    }
}

IDeptService :

package com.aaa.demo.service;

import com.aaa.demo.entity.Dept;

import java.util.List;

public interface IDeptService {
    List<Dept> listAll();
    int add(Dept dept);
}

DeptController :

package com.aaa.demo.controller;

import com.aaa.demo.entity.Dept;
import com.aaa.demo.service.IDeptService;
import com.aaa.demo.util.CommonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/dept")
public class DeptController {
    @Autowired
    private IDeptService deptService;

    @GetMapping("/list") //注意:这里是GetMapping
    public CommonResult listAll(){
        List<Dept> deptList=deptService.listAll();
        return CommonResult.success(deptList);
    }

    @PostMapping("/add") //注意:这里是PostMapping
    public CommonResult add(@RequestBody Dept dept){
        //@RequestBody:用于接收json字符串格式的对象参数
        int count=deptService.add(dept);
        return CommonResult.success(count);
    }

}


在这里插入图片描述

CommonResult:

package com.aaa.demo.util;

import lombok.Data;

@Data
public class CommonResult<T> {
    //状态编码:0成功,1失败
    private Integer code;
    //提示信息
    private String msg;
    //记录数
    private long count;
    //数据结果
    private T data;

    public CommonResult() {
    }

    public CommonResult(Integer code, String msg, long count, T data) {
        this.code = code;
        this.msg = msg;
        this.count = count;
        this.data = data;
    }

    //返回成功结果:增删改,或其他不返回记录数的操作
    public static <T> CommonResult success(T data){
        return new CommonResult(0,"success",0,data);
    }

    //返回成功结果:针对分页查询
    public static <T> CommonResult success(long count,T data){
        return new CommonResult(0,"success",count,data);
    }

    //返回失败
    public static <T> CommonResult fail(T data){
        return new CommonResult(1,"fail",0,data);
    }
}

SimpleCORSFilter :

package com.aaa.demo.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class SimpleCORSFilter implements Filter {
    private boolean isCross = false;
    @Override
    public void destroy() {
        isCross = false;
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        if (isCross) {
            HttpServletRequest httpServletRequest = (HttpServletRequest) request;
            HttpServletResponse httpServletResponse = (HttpServletResponse) response;
            //使用通配符 * 允许所有域名发起的跨域请求
            httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
            //允许访问的方式
            httpServletResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
            //表示每次异步请求都发起预检请求,也就是说,发送两次请求。 resp.addHeader("Access-Control-Max-Age", "1800"),表示隔30分钟才发起预检请求。也就是说,发送两次请求
            httpServletResponse.setHeader("Access-Control-Max-Age", "0");
            //允许携带的头
            httpServletResponse.setHeader("Access-Control-Allow-Headers",
                    "Origin, No-Cache, X-Requested-With, If-Modified-Since, Pragma, Last-Modified, Cache-Control, Expires, Content-Type, X-E4M-With,userId,token");
            //是否允许后续请求携带认证信息(cookies),该值只能是true,否则不返回。这个是服务端下发到客户端的 response 中头部字段,意义是允许客户端携带验证信息,例如 cookie 之类的。
            httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
            //代表javascript和Ajax的跨域请求
            httpServletResponse.setHeader("XDomainRequestAllowed", "1");
        }
        chain.doFilter(request, response);
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        String isCrossStr = filterConfig.getInitParameter("IsCross");
        isCross = isCrossStr.equals("true") ? true : false;
        System.out.println(isCrossStr);
    }

}

配置tomcat 并运行项目:

在这里插入图片描述

vue—前台搭建:

新建空项目文件:

在这里插入图片描述

在项目文件目录地址栏—cmd:

在这里插入图片描述

在cmd窗口执行命令:

在这里插入图片描述

Microsoft Windows [版本 10.0.22000.978]
(c) Microsoft Corporation。保留所有权利。

D:\java-Vue-space\0927_ssm_vue_KTLX>vue create web_front_0927


Vue CLI v4.1.1
┌─────────────────────────────────────────┐
│                                         │
│   New version available 4.1.1 → 5.0.8   │
│    Run npm i -g @vue/cli to update!     │
│                                         │
└─────────────────────────────────────────┘

? Please pick a preset: Manually select features
? Check the features needed for your project: Babel, Router, Vuex
? Use history mode for router? (Requires proper server setup for index fallback in production) No
? Where do you prefer placing config for Babel, ESLint, etc.? In package.json
? Save this as a preset for future projects? No


Vue CLI v4.1.1
✨  Creating project in D:\java-Vue-space\0927_ssm_vue_KTLX\web_front_0927.
🗃  Initializing git repository...
⚙  Installing CLI plugins. This might take a while...


> core-js@3.25.3 postinstall D:\java-Vue-space\0927_ssm_vue_KTLX\web_front_0927\node_modules\core-js
> node -e "try{require('./postinstall')}catch(e){}"


> ejs@2.7.4 postinstall D:\java-Vue-space\0927_ssm_vue_KTLX\web_front_0927\node_modules\ejs
> node ./postinstall.js

added 1259 packages from 631 contributors in 239.437s

94 packages are looking for funding
  run `npm fund` for details

🚀  Invoking generators...
📦  Installing additional dependencies...

added 11 packages from 40 contributors in 16.939s

95 packages are looking for funding
  run `npm fund` for details

⚓  Running completion hooks...

📄  Generating README.md...

🎉  Successfully created project web_front_0927.
👉  Get started with the following commands:

 $ cd web_front_0927
 $ npm run serve


D:\java-Vue-space\0927_ssm_vue_KTLX> cd web_front_0927

D:\java-Vue-space\0927_ssm_vue_KTLX\web_front_0927> npm run serve

> web_front_0927@0.1.0 serve D:\java-Vue-space\0927_ssm_vue_KTLX\web_front_0927
> vue-cli-service serve

 INFO  Starting development server...
98% after emitting CopyPlugin

 DONE  Compiled successfully in 5123ms                                                                          19:30:23


  App running at:
  - Local:   http://localhost:8080/
  - Network: http://192.168.31.110:8080/

  Note that the development build is not optimized.
  To create a production build, run npm run build.


命令执行完成并生成网址访问链接:

在这里插入图片描述

复制链接到浏览器+回车:

在这里插入图片描述

在vue脚手架项目上修改成需要的功能页面:

代码整体布局:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在vscode中打开《生成的》项目文件:

在这里插入图片描述
在这里插入图片描述

修改编辑项目文件:

在这里插入图片描述

App.vue :

<template>
  <div id="app">
    <router-view/>
  </div>
</template>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

#nav {
  padding: 30px;
}

#nav a {
  font-weight: bold;
  color: #2c3e50;
}

#nav a.router-link-exact-active {
  color: #42b983;
}
</style>

在这里插入图片描述

views—Login.vue :

<template>
    <div>
        <table border="1" align="center">
            <tr>
                <td>用户名</td>
                <td>
                    <input type="text" v-model="user.username" />
                </td>
            </tr>
            <tr>
                <td>密码</td>
                <td>
                    <input type="password" v-model="user.password" />
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="button" value="登录" @click="login" />
                </td>
            </tr>
        </table>
    </div>
</template>

<script>
    export default{
         //配置组件需要的数据属性
         data(){
            return{
                user:{
                    username:"",
                    password:""
                }
            }
         },
         methods:{
            login(){
                alert(this.user.username+" "+this.user.password);
                //跳转到后台页面
                this.$router.push({name:"AdminWelcome"});
            }
        }
    }
</script>

在这里插入图片描述

router—index.js(部分)

import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'

//在vue实例中使用路由组件
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect:"/login" //路径重定向
  },
  {
    path: '/login',  //地址路径
    name: 'Login',    //地址命名
    component:Login
  }
]

//创建路由对象
const router = new VueRouter({
  routes
})

//导出路由对象
export default router

views—AdminWelcome.vue:

<template>
    <h1>欢迎使用后台管理系统</h1>
</template>

<script lang="ts">
    import Vue from 'vue'
    export default Vue.extend({
        
    })
</script>

保存修改,登录页面:

在这里插入图片描述
在这里插入图片描述

根据项目布局结构/联系,整理代码:

在这里插入图片描述

router—index.js:

import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'

//在vue实例中使用路由组件
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect:"/login" //路径重定向
  },
  {
    path: '/login',  //地址路径
    name: 'Login',    //地址命名
    component:Login
  },
  {
    path: '/elui',  
    name: 'ELUi',    
    component:()=>import("../views/ELUiTest")
  },
  {
    path:"adminhome",
    name:"AdminHome",
    component:()=>import("../views/AdminHome"),
    children:[ //配置子级视图的页面
      {
        path:"",
        name:"AdminWelcome",
        component:()=>import("../views/AdminWelcome")
      },
      {
        path:"deptMgr",
        name:"DeptMgr",
        component:()=>import("../views/DeptMgr")
      }
    ]
  }
]

//创建路由对象
const router = new VueRouter({
  routes
})

//导出路由对象
export default router

util—AxiosUtil.js:

//导入axios模块
import axios from 'axios'
//配置axios模块
let axiosUtil=axios.create({
    baseURL:"http://localhost:8080/0927_ssm_vue_KTLX_war_exploded/api/" //配置axios组件请求的固定前缀
}) 

//到处具有特定配置的axios对象
export default axiosUtil;

service—DeptService.js:

//导入axios模块
import axiosUtil from "../util/AxiosUtil";
//定义业务方法,实现后台接口请求
//查询
function list(){
    //返回请求指定Controller的一个promise对象(ajax异步请求对象)
    return axiosUtil.get("dept/list");
}
//添加
function add(dept){
    return axiosUtil.post("dept/add",dept);
}

//当前是一个js module(模块),如果想要当前模块的内容,被其他模块使用,需要进行导出
export default{
    list,add
}

views—DeptMgr.vue:

<template>
    <div>
        <table border="1" align="center">
            <tr>
                <th>部门编号</th>
                <th>部门名称</th>
            </tr>
            <tr v-for="(d,index) in depts" :key="index">
                <td>{{d.deptId}}</td>
                <td>{{d.deptName}}</td>
            </tr>
        </table>
        <hr/>
        <div class="add">
            部门名称:
            <input type="text" v-model="dept.deptName" />
            <input type="button" value="添加" @click="add" />
        </div>
    </div>
</template>

<script>
    //import axiosUtil from '../util/AxiosUtil'
    //导入部门业务层对象
    import deptService from '../service/DeptService'

    export default{
        data(){
            return{
                depts:[],
                dept:{
                    deptId:"",
                    deptName:""
                }
            }
        },
        methods:{
            list(){  //获取部门数据
                deptService.list().then(resp=>{
                    this.depts=resp.data.data;
                })
                
                // axiosUtil.get("dept/list").then(resp=>{
                //     this.depts=resp.data.data;
                // })
                //Promise:异步调用对象
                // var p = axios.get("http://localhost:8080/api/dept/list");
                // p.then(resp=>{
                //     this.depts=resp.data.data;
                // })
            },
            add(){
                //使用axios向后台发送post请求
                deptService.add(this.dept).then(resp=>{
                     //let:定义局部变量的关键字
                     let res=resp.data;
                     if(res.code==0){
                        alert("添加成功");
                        this.dept.deptName="";
                        this.list();
                     }
                })

                // axios.post("http://localhost:8080/api/dept/add",this.dept).then(resp=>{
                //     let res = resp.data;
                //     if(res.code==0){
                //         alert("添加成功");
                //         this.dept.deptName="";
                //         this.list();
                //     }
                // })
            }
        },
        created(){  //vue生命周期函数,vue实例创建之后
            this.list();
        }
    }
</script>

components—SideBar.vue:

<template>
    <ul>
        <li>
            <router-link :to="{name:'DeptMgr'}">部门管理</router-link>
        </li>
        <li>
            <router-link :to="{name:'EmpMgr'}">员工管理</router-link>
        </li>
    </ul>
</template>

<script>
    export default{
        
    }
</script>

views—AdminHome.vue:

<template>
    <div id="con">
        <div id="top"><h3>这是后台管理系统</h3></div>
        <div id="sidebar">
            <!--引用子级组件-->
            <SideBar/>
        </div>
        <div id="main">
            <!--要根据不同地址,显示不同的内容页面-->
            <router-view/>
        </div>
    </div>
</template>
<script>
    //因为该页面需要使用,菜单栏组件,所以进行导入
    import SideBar from "../components/SideBar.vue"

    export default{
        data(){
            return{

            }
        },
        components:{ //当前组件中,使用其他子级组件
            SideBar
        }
    }
</script>

<style scoped>
    #con{
        width: 800px;
        height:500px;
        border:1px solid gray;
        position:relative;
        margin:0px auto;
    }
    #top{
        position: absolute;
        top:0px;
        left:0px;
        height:50px;
        width:800px;
        background-color: aliceblue;
    }
    #sidebar{
        width:150px;
        height:450px;
        position:absolute;
        left:0px;
        top:50px;
        background: lightblue;
    }
    #main{
        width:650px;
        height:450px;
        position:absolute;
        right:0px;
        top:50px;
    }
</style>

在这里插入图片描述

Error①Failed to compile:

在这里插入图片描述
在这里插入图片描述

Error②端口被占用:

在这里插入图片描述

在这里插入图片描述

运行结果如下:

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

参考:

在这里插入图片描述
axios中文文档|axios中文网
http://www.axios-js.com/zh-cn/docs/
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/118016.html

(0)
seven_的头像seven_bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!