基于《狂神说Java》Vue--学习笔记

编程知识 更新时间:2023-05-03 01:33:21

前言:

本笔记仅做学习与复习使用,不存在刻意抄袭。

------------------------------------------------------------------------------------------------------------

给各位学友强烈推荐《遇见狂神说》他的整套Java学习路线使我获益匪浅!!!

点击跳转至遇见狂神说哔哩哔哩首页

如果你也是狂神的小迷弟,可以加我好友一起探讨学习。
 


目录

前言:

前端核心分析

VUE概述

前端三要素

JavaScript框架

 第一个Vue框架

IDEA 安装Vue插件

Vue的基本语法

简单绑定元素

vue-bind

v-if v-else

 v-for

 v-on 事件绑定

Vue双向绑定v-model

什么是双向绑定

为什么要实现数据的双向绑定

在表单中使用双向数据绑定

组件(重要)

Axios

什么是Axios

为什么要使用Axios

后端项目

新建一个项目

 测试运行

创建数据库

导入依赖

Axios的使用

跨域问题

Vue 计算属性、内容分发、自定义事件

 计算属性(重点及特色)

总结

内容分发(插槽)

自定义事件(重点)

Vue入门小结

第一个Vue-cli项目

Vue-cli简介

环境配置

 第一个vue-cli应用程序

webpack的使用

安装Webpack

使用webpack

Vue vue-router路由

安装

测试路由

Vue+ElementUI

创建工程

创建登录页面

路由嵌套

参数传递和重定向

参数传递

重定向

路由模式、404和路由钩子

路由模式

404页面

路由钩子


前端核心分析

VUE概述

Vue (读音/vju/, 类似于view)是一套用于构建用户界面的渐进式框架,发布于2014年2月。与其它大型框架不同的是,Vue被设计为可以自底向上逐层应用。Vue的核心库只关注视图层,不仅易于上手,还便于与第三方库(如: vue-router: 跳转,vue-resource: 通信,vuex:管理)或既有项目整合
 

前端三要素

  • HTML (结构) :超文本标记语言(Hyper Text Markup Language) ,决定网页的结构和内容
  • CSS (表现) :层叠样式表(Cascading Style sheets) ,设定网页的表现样式
  • JavaScript (行为) :是一种弱类型脚本语言,其源代码不需经过编译,而是由浏览器解释运行,用于控制网页的行为

JavaScript框架

  • jQuery: 大家熟知的JavaScript框架,优点是简化了DOM操作,缺点是DOM操作太频繁,影响前端性能;在前端眼里使用它仅仅是为了兼容IE6、7、8;
  • Angular: Google收购的前端框架,由一群Java程序员开发,其特点是将后台的MVC模式搬到了前端并增加了模块化开发的理念,与微软合作,采用TypeScript语法开发;对后台程序员友好,对前端程序员不太友好;最大的缺点是版本迭代不合理(如: 1代-> 2代,除了名字,基本就是两个东西;截止发表博客时已推出了Angular6)
  • React: Facebook出品,一款高性能的JS前端框架;特点是提出了新概念[虚拟DOM]用于减少真实DOM操作,在内存中模拟DOM操作,有效的提升了前端渲染效率;缺点是使用复杂,因为需要额外学习一门[JSX] 语言;
  • Vue:一款渐进式JavaScript框架,所谓渐进式就是逐步实现新特性的意思,如实现模块化开发、路由、状态管理等新特性。其特点是综合了Angular (模块化)和React (虚拟DOM)的优点;
  • Axios :前端通信框架;因为Vue 的边界很明确,就是为了处理DOM,所以并不具备通信能力,此时就需要额外使用一个通信框架与服务器交互;当然也可以直接选择使用jQuery提供的AJAX通信功能;
  • 前端三大框架:Angular、React、Vue
     

 第一个Vue框架

MVVM (Model-View-ViewModel) 是一种软件架构设计模式,由微软WPF (用于替代WinForm,以前就是用这个技术开发桌面应用程序的)和Silverlight (类似于Java Applet,简单点说就是在浏览器上运行的WPF)的架构师Ken Cooper和Ted Peters 开发,是一种简化用户界面的事件驱动编程方式。由John Gossman (同样也是WPF和Silverlight的架构师)于2005年在他的博客上发表。

MVVM 源自于经典的MVC (ModI-View-Controller) 模式。MVVM的核心是ViewModel层,负责转换Model中的数据对象来让数据变得更容易管理和使用,其作用如下:

  • 该层向上与视图层进行双向数据绑定
  • 向下与Model层通过接口请求进行数据交互

IDEA 安装Vue插件

这里直接在idea设置中安装插件即可:

 如果,你用的idea是2020版,且插件搜索不到的,可以安装idea2022最新版。如何破解大家可以自行百度。

Vue的基本语法

好!只要安装了插件其实就可以先写一个简单的页面来感受一下Vue的使用:

我们随便创建一个.html文件就好。

简单绑定元素

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<!--view层-->
<div id="app">
  {{ message }}
</div>
<!--导入vue.js-->
<script src="https://cdn.jsdelivr/npm/vue@2.5.16/dist/vue.js"></script>
<script>
  var vm=new Vue({
    el: '#app',
    //Model层
    data: {
      message: "hello world,狂神666"
    }
  });
</script>
</body>
</html>

 

 注意,这里是直接用的vue在线cdn:

https://cdn.jsdelivr/npm/vue@2.5.16/dist/vue.js

vue-bind

itle绑定message元素使得鼠标悬停可以显示

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<!--view层-->
<div id="app">

    <span v-bind:title="message">鼠标悬浮</span>
</div>
<!--导入vue.js-->
<script src="https://cdn.jsdelivr/npm/vue@2.6.10/dist/vue.js"></script>
<script>
    var vm=new Vue({
        el: '#app',
        //Model层
        data: {
            message: "hello world"
        }
    });
</script>
</body>
</html>

运行后,鼠标悬停在<鼠标悬浮>就会显示hello world

v-if v-else

其效果类似于java中if,else条件选择语句

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<!--view层-->
<div id="app">
  <h1 v-if="chose">如果chose是{{chose}},我就显示{{chose}}</h1>
  <h1 v-else>如果chose是{{chose}},我就显示{{chose}}</h1>
  <h1 v-if="type==='A'">如果type是{{type}},我就显示{{type}}</h1>
  <h1 v-else-if="type==='B'">如果type是{{type}},我就显示{{type}}</h1>
  <h1 v-else-if="type==='C'">如果type是{{type}},我就显示{{type}}</h1>
</div>
<!--导入vue.js-->
<script src="https://cdn.jsdelivr/npm/vue@2.6.10/dist/vue.js"></script>
<script>
  var vm=new Vue({
    el: '#app',
    //Model层
    data: {
      chose: false,
      type: 'B'
    }
  });
</script>
</body>
</html>

 v-for

看到for,各位就知道这玩意可能跟循环挂钩,它真就是循环,而且代码量极少!

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<!--view层-->
<div id="app">
  <h1 v-for="item in items">
    {{item.course}}
  </h1>
</div>
<!--导入vue.js-->
<script src="https://cdn.jsdelivr/npm/vue@2.6.10/dist/vue.js"></script>
<script>
  var vm=new Vue({
    el: '#app',
    //Model层
    data: {
      items: [
        {course: 'java'},
        {course: 'vue'},
        {course: 'html'},
        {course: 'C#'},
        {course: 'redis'},
        {course: 'ES'}
      ]
    }
  });
</script>
</body>
</html>

 结果如下:

 v-on 事件绑定

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<!--view层-->
<div id="app">
  <button v-on:click="sayHi('我是参数')">有种你点我啊!!!</button>
</div>
<!--导入vue.js-->
<script src="https://cdn.jsdelivr/npm/vue@2.6.10/dist/vue.js"></script>
<script>
  var vm=new Vue({
    el: '#app',
    //Model层
    data: {
      message: "年轻人,出来混,不是打打杀杀,是人情世故!"
    },
    methods: {
      sayHi: function (e){
        alert(this.message+e);
      }
    }
  });
</script>
</body>
</html>

 点击按钮后,弹窗显示消息。

Vue双向绑定v-model

什么是双向绑定

Vue.js是一个MVVM框架,即数据双向绑定,即当数据发生变化的时候,视图也就发生变化,当视图发生变化的时候,数据也会跟着同步变化。这也算是Vue.js的精髓之处了。

​ 值得注意的是,我们所说的数据双向绑定,一定是对于UI控件来说的,非UI控件不会涉及到数据双向绑定。单向数据绑定是使用状态管理工具的前提。如果我们使用vuex,那么数据流也是单项的,这时就会和双向数据绑定有冲突。

就像是在输入框中输入数据,下面的元素值显示出来


为什么要实现数据的双向绑定

在Vue.js 中,如果使用vuex ,实际上数据还是单向的,之所以说是数据双向绑定,这是用的UI控件来说,对于我们处理表单,Vue.js的双向数据绑定用起来就特别舒服了。即两者并不互斥,在全局性数据流使用单项,方便跟踪;局部性数据流使用双向,简单易操作。

在表单中使用双向数据绑定

你可以用v-model指令在表单 、 及 元素上创建双向数据绑定。它会根据控件类型自动选取正确的方法来更新元素。尽管有些神奇,但v-model本质上不过是语法糖。它负责监听户的输入事件以更新数据,并对一些极端场景进行一些特殊处理。

​ 注意:v-model会忽略所有元素的value、checked、selected特性的初始值而总是将Vue实例的数据作为数据来源,你应该通过JavaScript在组件的data选项中声明
 

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<div id="app">
  输入的文本:<input type="text" v-model="message"/>{{ message }}
  <br/>
  性别:<input type="radio" name="sex" value="男" v-model="luyi" >男
  <input type="radio" value="女" name="sex" v-model="luyi" >女
  <p>
    选择了谁:{{luyi}}
  </p>
  下拉框 :<select v-model="selected">
  <option value="" disabled>--请选择--</option>
  <option>A</option>
  <option>B</option>
  <option>C</option>
</select>
  <span>下拉框选中了:{{selected}}</span>
</div>
<!--导入vue.js-->
<script src="https://cdn.jsdelivr/npm/vue@2.5.16/dist/vue.js"></script>
<script>
  var vm=new Vue({
    el:'#app',
    data: {
      message: "hello,its me",
      checked: false,
      luyi: '',
      selected: ''
    },
  });
</script>
</body>
</html>

组件(重要)

​组件是可复用的Vue实例,说白了就是一组可以重复使用的模板,跟JSTL的自定义标签、Thymeleaf的th:fragment 等框架有着异曲同工之妙。通常一个应用会以一棵嵌套的组件树的形式来组织:

自定义组件在vue中是很重要的知识点,如果你看到这里,希望你配合视频学习,本人作为初学者,可能不能很好的为你讲清楚。

首先先看一下代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<!--view层-->
<div id="app">
  <!--组件,传递给组件中的值:props-->
  <libing v-for="item in items" v-bind:libing="item.course"></libing>
</div>
<!--导入vue.js-->
<script src="https://cdn.jsdelivr/npm/vue@2.6.10/dist/vue.js"></script>
<script>
  //定义一个Vue组件
  Vueponent('libing',{
    props: ['libing'],
    template: '<h1>{{libing}}</h1>'
  });
  var vm=new Vue({
    el: '#app',
    //Model层
    data: {
      items:[
        {course: 'java'},
        {course: 'vue'},
        {course: 'html'},
        {course: 'C#'},
        {course: 'redis'},
        {course: 'ES'}
      ]
    }
  });
</script>
</body>
</html>

 运行结果如下:

接下来就是Vue的重头戏了!!

前端如何跟后端产生交互呢,前端将要渲染的数据从哪里来呢?

这里需要讲一下题外话:前后端分离,在前后端分离时代,就是前端,通过发起一个请求,后端接口接受到对应的请求之后,查询到数据库中的数据,将数据转换成Json字符串,再传给前端,这样,前端就能得到数据,然后想干啥就干啥了!

而Vue作为一个纯粹的视图层框架,其是没有内置与后端交互的工具的。

这时Axios就闪亮登场了。

Axios

什么是Axios

Axios是一个开源的可以用在浏览器端和NodeJS 的异步通信框架,她的主要作用就是实现AJAX异步通信,其功能特点如下:

从浏览器中创建XMLHttpRequests

从node.js创建http请求

支持Promise API [JS中链式编程]

拦截请求和响应

转换请求数据和响应数据

取消请求

自动转换JSON数据

客户端支持防御XSRF (跨站请求伪造)

GitHub: https://github/ axios/axios
中文文档: http://www.axios-js/


为什么要使用Axios

由于Vue.js是一个视图层框架且作者(尤雨溪) 严格准守SoC (关注度分离原则),所以Vue.js并不包含Ajax的通信功能,为了解决通信问题,作者单独开发了一个名为vue-resource的插件,不过在进入2.0 版本以后停止了对该插件的维护并推荐了Axios 框架。少用jQuery,因为它操作Dom太频繁 !
 

接下来我们就来走一下前后端交互的流程:

后端项目

新建一个项目

 

 测试运行

package com.libing.axios.controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * @author liar
 */
@RestController
public class TestController {
    @RequestMapping("/test")
    public String test(){
        return "hello controller";
    }
}

ok!项目能正常跑起来,我们就可以写代码了。

创建数据库

如果要问为什么这么创建,详情请看《狂神说Java》mybatis-plus课程。

导入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache/POM/4.0.0" xmlns:xsi="http://www.w3/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache/POM/4.0.0 https://maven.apache/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.7.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.libing</groupId>
    <artifactId>axios</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>axios</name>
    <description>axios</description>
    <properties>
        <java.version>8</java.version>
        <repackage.classifier/>
        <spring-native.version>0.12.0</spring-native.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!--mybatis-plus 是自己开发的,非官方的-->
        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-boot-starter</artifactId>
            <version>3.5.1</version>
        </dependency>

        <dependency>
            <groupId>com.baomidou</groupId>
            <artifactId>mybatis-plus-generator</artifactId>
            <version>3.4.1</version>
        </dependency>
        <!--swagger2和ui的依赖-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>2.0.1</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.21</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                    <classifier>${repackage.classifier}</classifier>
                    <image>
                        <builder>paketobuildpacks/builder:tiny</builder>
                        <env>
                            <BP_NATIVE_IMAGE>true</BP_NATIVE_IMAGE>
                        </env>
                    </image>
                </configuration>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/release</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <id>spring-releases</id>
            <name>Spring Releases</name>
            <url>https://repo.spring.io/release</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>
    <profiles>
        <profile>
            <id>native</id>
            <properties>
                <repackage.classifier>exec</repackage.classifier>
                <native-buildtools.version>0.9.11</native-buildtools.version>
            </properties>
            <dependencies>
                <dependency>
                    <groupId>org.junit.platform</groupId>
                    <artifactId>junit-platform-launcher</artifactId>
                    <scope>test</scope>
                </dependency>
            </dependencies>
        </profile>
    </profiles>

</project>

配置application



spring.mvc.pathmatch.matching-strategy=ant_path_matcher

#数据库连接配置
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_plus?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=GMT%2B8
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver




#配置日志
mybatis-plus.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl


mybatis-plus.global-config.db-config.logic-delete-field=deleted
mybatis-plus.global-config.db-config.logic-delete-value=0
mybatis-plus.global-config.db-config.logic-not-delete-value=1

配置MybatisPlusConfig注册乐观锁插件

package com.libing.axios.axios_test.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * @author liar
 */
@MapperScan("com.libing.axios.axios_test.mapper") //扫描mapper文件夹
@EnableTransactionManagement
@Configuration   //配置类
public class MybatisPlusConfig {
    //注册乐观锁插件
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return interceptor;
    }






}

配置MyMetaObjectHandler用于填充策略

package com.libing.axios.axios_test.handler;



import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author liar
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override   //插入时的填充策略
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill");
        //setFieldValByName(String fieldName, Object fieldVal, MetaObject metaObject)
        this.setFieldValByName("createTime",new Date(),metaObject);
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
    @Override  //跟新时的填充策略
    public void updateFill(MetaObject metaObject) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        this.setFieldValByName("updateTime",new Date(),metaObject);
    }
}

配置自动生成代码工具类AutoGenerationCode

package com.libing.axios.utils;


import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableFill;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liar
 */
public class AutoGenerationCode {
    public static void main(String[] args) {
//        //获取控制台的数据
//        Scanner scanner = new Scanner(System.in);
        // 构建一个代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");//获取当前目录
        gc.setOutputDir(projectPath + "/src/main/java");      //生成文件的输出目录
        gc.setAuthor("liar");                                  //作者
        gc.setFileOverride(true);				              //是否覆蓋已有文件 默认值:false
        gc.setOpen(false);                                    //是否打开输出目录 默认值:true
        gc.setIdType(IdType.AUTO);  //id自增
        gc.setSwagger2(true);  //自动配置swagger文档
        gc.setBaseColumnList(true);				              //开启 baseColumnList 默认false
        gc.setBaseResultMap(true);				               //开启 BaseResultMap 默认false
//      gc.setEntityName("%sEntity");			//实体命名方式  默认值:null 例如:%sEntity 生成 UserEntity
//        gc.setMapperName("%sMapper");			                //mapper 命名方式 默认值:null 例如:%sDao 生成 UserDao
//        gc.setXmlName("%sMapper");				                //Mapper xml 命名方式   默认值:null 例如:%sDao 生成 UserDao.xml
//        gc.setServiceName("%sService");			                //service 命名方式   默认值:null 例如:%sBusiness 生成 UserBusiness
//        gc.setServiceImplName("%sServiceImpl");	                //service impl 命名方式  默认值:null 例如:%sBusinessImpl 生成 UserBusinessImpl
//        gc.setControllerName("%sController");	//controller 命名方式    默认值:null 例如:%sAction 生成 UserAction
//



        mpg.setGlobalConfig(gc);
// 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/mybatis_plus?useUnicode=true&useSSL=false&characterEncoding=utf8");
// dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("root");
        dsc.setDbType(DbType.MYSQL);
        mpg.setDataSource(dsc);
// 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName("axios_test");
//      pc.setParent("com.stu");

//        String name = scanner.nextLine();
        //自定义包配置
        pc.setParent("com.libing.axios");

        pc.setMapper("mapper");
        pc.setEntity("pojo");
        pc.setService("service");
//        pc.setServiceImpl("service.impl");
        pc.setController("controller");
        mpg.setPackageInfo(pc);
// 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
// to do nothing
            }
        };
        List<FileOutConfig> focList = new ArrayList<>();
        focList.add(new FileOutConfig("/templates/mapper.xml.ftl") {
            @Override
            public String outputFile(TableInfo tableInfo) {
// 自定义输入文件名称
                return projectPath + "/src/main/resources/mapper/" + /*pc.getModuleName() + "/" +*/
                        tableInfo.getEntityName() + "Mapper" +
                        StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        mpg.setTemplate(new TemplateConfig().setXml(null));
        // 策略配置	数据库表配置,通过该配置,可指定需要生成哪些表或者排除哪些表
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);	//表名生成策略
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);//数据库表字段映射到实体的命名策略, 未指定按照 naming 执行
//	    strategy.setCapitalMode(true);			    // 全局大写命名 ORACLE 注意
//	    strategy.setTablePrefix("prefix");		    //表前缀
//	    strategy.setSuperEntityClass("com.stu.domain");	//自定义继承的Entity类全称,带包名
//	    strategy.setSuperEntityColumns(new String[] { "test_id", "age" }); 	//自定义实体,公共字段
        strategy.setEntityLombokModel(true);	    //【实体】是否为lombok模型(默认 false
        strategy.setRestControllerStyle(true);	    //生成 @RestController 控制器
//	    strategy.setSuperControllerClass("com.baomidou.antmon.BaseController");	//自定义继承的Controller类全称,带包名
//      strategy.setInclude(scanner("表名"));		//需要包含的表名,允许正则表达式(与exclude二选一配置)
//        System.out.println("请输入映射的表名:");
//        String tables = scanner.nextLine();
//        String[] num = tables.split(",");
        strategy.setInclude("student");                       // 需要生成的表可以多张表
//	    strategy.setExclude(new String[]{"test"});      // 排除生成的表
//如果数据库有前缀,生成文件时是否要前缀acl_
//      strategy.setTablePrefix("bus_");
//      strategy.setTablePrefix("sys_");
        strategy.setLogicDeleteFieldName("deleted");


        strategy.setControllerMappingHyphenStyle(true);	    //驼峰转连字符
        strategy.setTablePrefix(pc.getModuleName() + "_");	//是否生成实体时,生成字段注解
//自动填充配置
        TableFill createTime = new TableFill("create_time", FieldFill.INSERT);
        TableFill updateTime = new TableFill("update_time", FieldFill.INSERT_UPDATE);
        ArrayList<TableFill> tableFills = new ArrayList<>();
        tableFills.add(createTime);
        tableFills.add(updateTime);
        strategy.setTableFillList(tableFills);
        //乐观锁
        strategy.setVersionFieldName("version");
        strategy.setControllerMappingHyphenStyle(true); //localhost:8080/hello_id_2
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }



}

如果这里看不懂,建议观看先看视频。【狂神说Java】MyBatisPlus最新完整教程通俗易懂。

 

 可以看到已经帮我们自动生成了代码。而且很规范。

注:这里要确定StudentMapper.xml中字段名与实体类中的字段名一致。

好接下来我们就可以写代码了:

StudentMapper

package com.libing.axios.axios_test.mapper;

import com.libing.axios.axios_test.pojo.Student;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author liar
 * @since 2022-06-16
 */
@Mapper
public interface StudentMapper extends BaseMapper<Student> {

    int setData(int age,String name,String address);
    List<Student> getData();
}

IStudentService

package com.libing.axios.axios_test.service;

import com.libing.axios.axios_test.pojo.Student;
import com.baomidou.mybatisplus.extension.service.IService;

import java.util.List;

/**
 * <p>
 *  服务类
 * </p>
 *
 * @author liar
 * @since 2022-06-16
 */
public interface IStudentService extends IService<Student> {
    int setData(int age, String name, String address);
    List<Student> getData();
}

StudentServiceImpl

package com.libing.axios.axios_test.service.impl;

import com.libing.axios.axios_test.pojo.Student;
import com.libing.axios.axios_test.mapper.StudentMapper;
import com.libing.axios.axios_test.service.IStudentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liar
 * @since 2022-06-16
 */
@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements IStudentService {

    @Autowired
    private StudentMapper studentMapper;
    @Override
    public int setData(int age, String name, String address) {
        Student student = new Student();
        student.setName(name);
        student.setAge(age);
        student.setAddress(address);
        return studentMapper.insert(student);
    }

    @Override
    public List<Student> getData() {
        return studentMapper.selectList(null);
    }
}

StudentController

package com.libing.axios.axios_test.controller;


import com.alibaba.fastjson.JSONArray;
import com.libing.axios.axios_test.service.impl.StudentServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author liar
 * @since 2022-06-16
 */
@Api( tags = "Student",description = "insert&List")
@RestController
@RequestMapping("/axios_test/student")
public class StudentController {

    @Autowired
    private StudentServiceImpl studentService;
    @RequestMapping("/getData")
    public String getData(){
        return JSONArray.toJSONString(studentService.getData());
    }
    @RequestMapping("/setData/{age}/{name}/{address}")
    public String setData(
            @PathVariable("age") int age,
            @PathVariable("name") String name,
            @PathVariable("address") String address

    ){
        int result = studentService.setData(age, name, address);

        if (result>0){
            return "添加成功";
        }else {
            return "添加失败";
        }
    }

}

启动类AxiosApplication

package com.libing.axios;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.oas.annotations.EnableOpenApi;

/**
 * @author liar
 */
@SpringBootApplication
@EnableOpenApi
@MapperScan("com.libing.axios.axios_test.mapper")
public class AxiosApplication {

    public static void main(String[] args) {
        SpringApplication.run(AxiosApplication.class, args);
    }

}

 后端,简单的插入和读取数据接口就写好了,现在我们启动服务测试!

首先我们先看看我们的接口在swagger中有没有显示:

 

 接下来测试插入数据。

数据库中也有了对应数据。

 现在测试获取数据:

 

 喔!测试成功了,现在可不得了,既然在开启后端服务的情况下访问http://localhost:8080/axios_test/student/getData可以得到json字符串,那我前端直接使用Axios访问这个地址,不就得到数据了,那我再把数据渲染到页面上,就大功告成了!

好的:话不多说,开整!

Axios的使用

这里将创建vue工程以及安装Axios的全流程走一遍,巩固一下基础。

在任意文件夹内打开cmd

输入   vue init webpack 项目名-vue     如vue init webpack hello-vue

接下来会自动下载模板   

C:\Users\liar\Desktop\Vue-Study>vue init webpack hello-vue

'git'      ڲ    ⲿ   Ҳ   ǿ    еij   
       ļ 
? Project name hello-vue   //项目名称
? Project description A Vue.js project
? Author liar    //作者
? Vue build standalone
? Install vue-router? No       //选择no
? Use ESLint to lint your code? No       //选择no
? Set up unit tests No       //选择no
? Setup e2e tests with Nightwatch? No       //选择no
? Should we run `npm install` for you after the project has been created? (recommended) no

   vue-cli · Generated "hello-vue".

# Project initialization finished!
# ========================

To get started:

  cd hello-vue
  npm install (or if using yarn: yarn)
  npm run dev

Documentation can be found at https://vuejs-templates.github.io/webpack


#进入工程目录

cd hello-vue

#安装vue-router

cnpm install vue-router --save-dev

#安装element-ui

npm i element-ui -S

#安装依赖

npm install

#安装SASS加载器

cnpm install sass-loader node-sass --save-dev

#启动测试

npm run dev

输入启动后的网址,见到这个页面就ok了。

接下来要么继续使用在线vue和axios要么下载对应的js文件。

我们我们编写index.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3/1999/xhtml">
<head>
  <meta charset="UTF-8">
  <title>Title</title>

</head>
<body>
<div id="app" >
  <div v-for="(site,index) in sites">
    <p>序号是:{{index}}</p>
    <p>名字是:{{site.name}}</p>
    <p>年龄是:{{site.age}}</p>
    <p>地址是:{{site.address}}</p>
    <hr>
  </div>

</div>
<!--导入vue.js-->
<script src="/vue.js"></script>
<!--导入axios-->
<script src="/axios.min.js"></script>
<script>
  const vm = new Vue({
    el: '#app',
    data: {
        sites: [
          {
            age: '',
            name: '',
            address: ''
          }
        ]
    },
    created() {
      this.show();
    },
    mounted:function (){
    },
    methods:{
      show:function (){
        axios.get('http://localhost:8080/axios_test/student/getData').then(function (response){
          this.sites = response.data;
          console.log(this.sites);
        }.bind(this)).catch(function (error){
          console.log(error);
        });
      }
    }
  });
</script>
</body>
</html>

 

跨域问题

首先我们得知道什么是跨域,为什么会产生跨域:

因为浏览器有一个安全机制叫同源策略。同源就是指协议、域名、端口都一样,如果任意一项不一致就是不同源。简单点说就是,你的网页URL和你调用的接口URL不是一个地方的,浏览器觉得有安全风险,不想让你使用这个接口的数据。摘取于:老猿说开发。

举例说明跨域的几种情况:

如果你的页面URL是 http://www.aaa/zzz.htm ,那么接口地址如下几种情况

1. https://www.aaa/xxx (不同源,因为协议不同)

2. http://www.aaa:8080/xxx (不同源,因为端口不同)

3. http://www.bbb/xxx (不同源,因为域名不同)

4. http://abc.aaa/xxx (不同源,因为域名不同)

5. http://www.aaa/xxx (同源,协议、域名、端口均相同)

这里针对跨域问题:提出我使用得最多也是很简单的两种解决方案:

1.编写我们SpringMvcConfiguration配置类:

package com.libing.axios.axios_test.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class SpringMvcConfiguration implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("*")
                .allowedMethods("*")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
}

2.谷歌浏览器解决方案:

  • 鼠标右键点击谷歌浏览器图标,选择打开文件所在位置;
  • 导航栏输入cmd

  • 执行命令:

chrome.exe --disable-web-security --user-data-dir=C:\MyChromeUserFata

 然后在跳出来的谷歌页面访问刚才的网址:

 喔!成功了呢!

Vue 计算属性、内容分发、自定义事件

 计算属性(重点及特色)

计算属性的重点突出在属性两个字上(属性是名词),首先它是个属性其次这个属性有计算的能力(计算是动词),这里的计算就是个函数:简单点说,它就是一个能够将计算结果缓存起来的属性(将行为转化成了静态的属性),仅此而已;可以想象为缓存。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<!--view层,模板-->
<div id="app">
  <p>currentTime1:{{currentTime1()}}</p>
  <p>currentTime2:{{currentTime2}}</p>
</div>
<!--导入vue.js-->
<script src="/vue.js"></script>
<script type="text/javascript">
  var vm = new Vue({
    el:"#app",
    data:{
      message: '来了老弟!',
    },
    methods:{
      currentTime1:function(){
        return Date.now();//返回一个时间戳
      }
    },
    computed:{
      currentTime2:function(){//计算属性:methods,computed方法名不能重名,重名之后,只会调用methods的方法
        this.message;
        return Date.now()//返回一个时间戳
      }
    }
  });
</script>
</body>
</html>

注意:methods和computed里的东西不能重名,重名之后,只会调用methods的方法

说明:

methods:定义方法, 调用方法使用currentTime1(), 需要带括号

computed:定义计算属性, 调用属性使用currentTime2, 不需要带括号:this.message是为了能够让currentTime2观察到数据变化而变化

如何在方法中的值发生了变化,则缓存就会刷新!可以在控制台使用vm.message 改变下数据的值,再次测试观察效果!

 

 

总结

调用方法时,每次都需要讲行计算,既然有计算过程则必定产生系统开销,那如果这个结果是不经常变化的呢?此时就可以考虑将这个结果缓存起来,采用计算属性可以很方便的做到这点,计算属性的主要特性就是为了将不经常变化的计算结果进行缓存,以节约我们的系统开销

内容分发(插槽)

Vue.js中我们使用`元素作为承载分发内容的出口,可以称其为插槽,可以应用在组合组件的场景中。

需求:需要把下面的内容,让标题和内容通过插槽插入内容

<p>标题</p>
<ul>
    <li>abcd</li>
    <li>abcd</li>
    <li>abcd</li>
</ul>
  • 定义一个代办事情的组件
 Vueponent('todo',{
        template:'<div>\
                <div>代办事项</div>\
                <ul>\
                    <li>kuangshen study Java</li>\
                </ul>\
            </div>'
    });
  • 将上面的代码留出一个插槽,即slot
 Vueponent('todo',{
        template:'<div>\
                <slot"></slot>\
                <ul>\
                    <slot"></slot>\
                </ul>\
            </div>'
    });
  • 定义一个名为todo-title的待办标题组件 和 todo-items的待办内容组件
Vueponent('todo-title',{
        props:['title'],
        template:'<div>{{title}}</div>'
    });
   
//这里的index,就是数组的下标,使用for循环遍历的时候,可以循环出来!
    Vueponent("todo-items",{
        props:["item","index"],
        template:"<li>{{index+1}},{{item}}</li>"
    });

  • slot通过name和组件绑定
 Vueponent('todo',{
        template:'<div>\
                <slot name="todo-title"></slot>\
                <ul>\
                    <slot name="todo-items"></slot>\
                </ul>\
            </div>'
    });

  • 实例化Vue并初始化数据
  var vm = new Vue({
    el:"#vue",
    data:{
      title: '人员信息',
      info:[
       {
         name: '',
         age: '',
         address: ''
       }
     ]
    },
    mounted(){
      axios.get('http://localhost:8080/axios_test/student/getData').then(response=>(this.info = response.data))
    }
  • 将数据通过插槽插入预留出来的位置
<todo>
  <todo-title slot="todo-title" :title="title"></todo-title>
  <todo-items slot="todo-items" :item="items" v-for="items in info"></todo-items>
</todo>

说明:

​ slot:是绑定组件用的

​ :title --> 是v-bind:title的缩写

  • 完整代码
<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3/1999/xhtml">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<!--view层,模板-->
<div id="vue">
  <todo>
    <todo-title slot="todo-title" :title="title"></todo-title>
    <todo-items slot="todo-items" :item="items"
                v-for="(items,index) in info"
                :index="index"></todo-items>
  </todo>
</div>
<!--导入Vue.js-->
<script src="/vue.js"></script>
<!--导入axios-->
<script src="/axios.min.js"></script>
<script type="text/javascript">
  Vueponent('todo',{
    template: '<div>\
<slot name="todo-title"></slot>\
<ul>\
<slot name="todo-items"></slot>\
            </ul>\
            </div>'
  });
  Vueponent("todo-title",{
    props:['title'] ,
    template: '<div>{{title}}</div>'

  });
  Vueponent("todo-items",{
    props: ['item','index'],
    template: '<li>姓名是:{{item.name}}</li>'

  });
  var vm = new Vue({
    el:"#vue",
    data:{
      title: '人员信息',
      info:[
        {
          name: '',
          age: '',
          address: ''
        }
      ]
    },
    mounted(){
      axios.get('http://localhost:8080/axios_test/student/getData').then(response=>(this.info = response.data))
    }

  });
</script>
</body>
</html>

其运行长这样:

 

自定义事件(重点)

通过上诉代码我们可以发现一个问题,如果删除操作要在组件中完成,那么组件如何删除Vue实例中的数据?

删除按钮是在组件中的,点击删除按钮删除对应的数据。

阅读Vue教程可知,此时就涉及到参数传递与事件分发了, Vue为我们提供了自定义事件的功能很好的帮助我们解决了这个问题; 组件中使用this.$emit(‘自定义事件名’, 参数) ,而在视图层通过自定义事件绑定Vue中的删除操作的方法

<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3/1999/xhtml">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
</head>
<body>
<!--view层,模板-->
<div id="vue">
<todo>
  <todo-title slot="todo-title" :title="title"></todo-title>
  <todo-items slot="todo-items" :item="items"
              v-for="(items,index) in info"
              :index="index" v-on:remove="removeItems(items.name)"></todo-items>
</todo>
</div>
<!--导入Vue.js-->
<script src="/vue.js"></script>
<!--导入axios-->
<script src="/axios.min.js"></script>
<script type="text/javascript">
  Vueponent('todo',{
    template: '<div>\
<slot name="todo-title"></slot>\
<ul>\
<slot name="todo-items"></slot>\
            </ul>\
            </div>'
  });
Vueponent("todo-title",{
  props:['title'] ,
  template: '<div>{{title}}</div>'

});
  Vueponent("todo-items",{
    props: ['item','index'],
  template: '<li>姓名是:{{item.name}}<button @click="remove(item.name)">删除</button></li>',
    methods:{
      remove:function (name){
        this.$emit('remove',name);
      }
    }
  });
  var vm = new Vue({
    el:"#vue",
    data:{
      title: '人员信息',
      info:[
       {
         name: '',
         age: '',
         address: ''
       }
     ]
    },
    mounted(){
      axios.get('http://localhost:8080/axios_test/student/getData').then(response=>(this.info = response.data))
    },
    methods:{
      removeItems: function (name){
          axios.get('http://localhost:8080/axios_test/student/delData/'+name).then(response=>(
            axios.get('http://localhost:8080/axios_test/student/getData').then(response=>(this.info = response.data))
          ))
      }
    }
  });
</script>
</body>
</html>

这里我很难为读者讲清楚:详情请见狂神视频。

Vue入门小结

核心:数据驱动,组件化

优点:借鉴了AngularJS的模块化开发和React的虚拟Dom,虚拟Dom就是把Demo操作放到内存中执行;

常用的属性:

  • v-if
  • v-else-if
  • v-else
  • v-for
  • v-on绑定事件,简写@
  • v-model数据双向绑定
  • v-bind给组件绑定参数,简写:

组件化:

  • 组合组件slot插槽
  • 组件内部绑定事件需要使用到this.$emit(“事件名”,参数);
  • 计算属性的特色,缓存计算数据

遵循SoC关注度分离原则,Vue是纯粹的视图框架,并不包含,比如Ajax之类的通信功能,为了解决通信问题,我们需要使用Axios框架做异步通信;
 

第一个Vue-cli项目

Vue-cli简介

vue-cli官方提供的一个脚手架,用于快速生成一个vue的项目模板

预先定义好的目录结构及基础代码,就好比咱们在创建Maven项目时可以选择创建一个骨架项目,这个估计项目就是脚手架,我们的开发更加的快速

项目的功能

  • 统一的目录结构
  • 本地调试
  • 热部署
  • 单元测试
  • 集成打包上线

环境配置

  • Node.js

下载地址: http://nodejs/download/ 安装的时候一直下一步直到结束

确认是否安装成功:

  • 在cmd中运行node -v命令,查看是否能够输出版本号
  • 在cmd中运行npm -v命令,查看是否能够输出版本号

  • 安装node.js淘宝镜像加速器(cnpm)
# -g 就是全局安装
npm install cnpm -g

# 或使用如下语句解决npm速度慢的问题,但是每次install都需要(麻烦)
npm install --registry=https://registry.npm.taobao
cnpm instal1 vue-cli-g
#测试是否安装成功#查看可以基于哪些模板创建vue应用程序,通常我们选择webpack
vue list

 第一个vue-cli应用程序

  • 找到一个项目路径(空文件夹)

  • 创建一个基于webpack模板的vue应用程序

#1、首先需要进入到对应的目录 cd E:\study\Java\workspace\workspace_vue
#2、这里的myvue是顶日名称,可以根据自己的需求起名
vue init webpack myvue

创建过程需要的操作

一路选no

Project name:项目名称,默认回车即可
Project description:项目描述,默认回车即可
Author:项目作者,默认回车即可
Install vue-router:是否安装vue-router,选择n不安装(后期需要再手动添加)
Use ESLint to lint your code:是否使用ESLint做代码检查,选择n不安装(后期需要再手动添加)
Set up unit tests:单元测试相关,选择n不安装(后期需要再手动添加)
Setupe2etests with Nightwatch:单元测试相关,选择n不安装(后期需要再手动添加)
Should we run npm install for you after the,project has been created:创建完成后直接初始化,选择n,我们手动执行;运行结果

当出现问题时,它会给出提示我们按照提示来就行。

  • 初始化并运行

cd myvue
npm install
npm run dev

 访问localhost:8080

 看到这个页面就是成功了。

webpack的使用

安装Webpack

WebPack是一款模块加载器兼打包工具, 它能把各种资源, 如JS、JSX、ES 6、SASS、LESS、图片等都作为模块来处理和使用

安装

npm install webpack -g
npm install webpack-cli -g

测试安装成功:

webpack -v
webpack-cli -v

 配置

entry:入口文件, 指定Web Pack用哪个文件作为项目的入口
output:输出, 指定WebPack把处理完成的文件放置到指定路径
module:模块, 用于处理各种类型的文件
plugins:插件, 如:热更新、代码重用等
resolve:设置路径指向
watch:监听, 用于设置文件改动后直接打包
 

module.exports = {
	entry:"",
	output:{
		path:"",
		filename:""
	},
	module:{
		loaders:[
			{test:/\.js$/,;\loade:""}
		]
	},
	plugins:{},
	resolve:{},
	watch:true
}

使用webpack

  • 创建项目

在workspace中创建文件夹webpack-study,然后用IDEA打开

  • 创建一个名为modules的目录,用于放置JS模块等资源文件
  • 在modules下创建模块文件hello.js
//暴露一个方法
exports.sayHi = function(){
    document.write("<h1>狂神说es6</h1>")
}
  • 在modules下创建一个名为main.js的入口文件main.js,用于打包时设置entry属性
//require 导入一个模块,就可以调用这个模块中的方法了
var hello = require("./hello");
hello.sayHi();
  • 在项目目录下创建webpack.config.js配置文件,使用webpack命令打包
module.exports = {
    entry:"./modules/main.js",
    output:{
        filename:"./js/bundle.js"
    }
}

打包:

说明:打包如果失败,就用管理员权限运行webpack

  • 在项目目录下创建HTML页面,如index.html,导入webpack打包后的JS文件
<!doctype html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>狂神说Java</title>
    </head>
    <body>
        <script src="dist/js/bundle.js"></script>
    </body>
</html>

运行结果是:

 

# 参数--watch 用于监听变化,如果要打包的东西有变化,就重新打包
webpack --watch

Vue vue-router路由

安装

  • 基于第一个vue-cli进行测试学习; 先查看node modules中是否存在vue-router, vue-router是一个插件包, 所以我们还是需要用n pm/cn pm来进行安装的

npm install vue-router --save-dev

  • 如果在一个模块化工程中使用它,必须要通过Vue.use()明确地安装路由功能
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter);

测试路由

  • 删除第一个vue-cli项目中的没用的东西
  • components 目录下存放我们自己编写的组件
  • 定义几个自己的组件 Content.vue 、Main.vue、Test.vue

Content.vue

<template>
	<div>
		<h1>内容页</h1>
	</div>
</template>

<script>
	export default {
		name:"Content"
	}
</script>

Main.vue

<template>
<div>
    <h1>首页</h1>
    </div>
</template>

<script>
    export default {
        name:"Main"
    }
</script>

Test.vue

<template>
<h1>测试页</h1>
</template>

<script>
export default {
  name: "Test"
}
</script>

<style scoped>

</style>
  • 安装路由,在src目录下,新建一个文件夹:router,专门存放路由,配置路由index.js
import Vue from 'vue'
import VueRouter from 'vue-router'
import Test from "../components/Test";
import Content from '../components/Content'
import Main from '../components/Main'
import Libing from '../components/Libing'
//安装路由

Vue.use(VueRouter);

//配置导出路由
export default new VueRouter({
    routes: [
        {
            //路由路径
            path: '/content',
            //名称,可以不写
            name: 'content',
            //跳转的组件
            component: Content
        },
        {
            //路由路径
            path: '/main',
            name: 'main',
            //跳转的组件
            component: Main
        },


        {
            //路由路径
            path: '/libing',
            name: 'libing',
            //跳转的组件
            component: Libing
        },
      {
        //路由路径
        path: '/test',
        name: 'test',
        //跳转的组件
        component: Test
      }
    ]
});
  • main.js中配置路由
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'//自动扫描里面的路由配置
Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  //配置路由
  router,
  components: { App },
  template: '<App/>'
})
  • App.vue中使用路由
<template>
  <div id="app">
    <h1>狂神132153313</h1>
    <router-link to="/main">首页</router-link>
    <router-link to="/content">内容页</router-link>
    <router-link to="/libing">libing页</router-link>
    <router-link to="/test">test页</router-link>

    <router-view></router-view>
  </div>
</template>
<script>

export default {
  name: 'App',
}
</script>
<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

运行npm run dev,然后浏览器访问localhost:8080

点击对应的标签,可以跳转到对应页面。

 

Vue+ElementUI

创建工程

  • 创建一个名为hello-vue的工程

vue init webpack hello-vue

  • 安装依赖, vue-router、element-ui、sass-loader和node-sass四个插件
#进入工程目录
cd hello-vue
#安装vue-routern 
npm install vue-router --save-dev
#安装element-ui
npm i element-ui -S
#安装依赖
npm install
# 安装SASS加载器
cnpm install sass-loader node-sass --save-dev
#启功测试
npm run dev
  • npm命令说明

npm install moduleName:安装模块到项目目录下

npm install -g moduleName:-g的意思是将模块安装到全局,具体安装到磁盘哪个位置要看npm

config prefix的位置

npm install -save moduleName:–save的意思是将模块安装到项目目录下, 并在package文件的dependencies节点写入依赖,-S为该命令的缩写

npm install -save-dev moduleName:–save-dev的意思是将模块安装到项目目录下,并在package文件的devDependencies节点写入依赖,-D为该命令的缩写

  • idea打开创建好的项目

创建登录页面

目录结构: 

说明:

  • assets:用于存放资源文件
  • components:用于存放Vue功能组件
  • views:用于存放Vue视图组件
  • router:用于存放vue-router配置
  • 在views目录下创建首页视图Main.vue组件
<template>
<div>首页</div>
</template>
<script>
    export default {
        name:"Main"
    }
</script>
<style scoped>
</style>
  • 在views目录下创建登录页面视图Login.vue组件
<template>
  <div>
    <el-form ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box">
      <h3 class="login-title">欢迎登录</h3>
      <el-form-item label="账号" prop="username">
        <el-input type="text" placeholder="请输入账号" v-model="form.username"/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" placeholder="请输入密码" v-model="form.password"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-on:click="onSubmit('loginForm')">登录</el-button>
      </el-form-item>
    </el-form>

    <el-dialog title="温馨提示" :visible.sync="dialogVisiable" width="30%" :before-close="handleClose">
      <span>请输入账号和密码</span>
      <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogVisible = false">确定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
    export default {
        name: "Login",
      data(){
          return{
            form:{
              username:'',
              password:''
            },
            //表单验证,需要在 el-form-item 元素中增加prop属性
            rules:{
              username:[
                {required:true,message:"账号不可为空",trigger:"blur"}
              ],
              password:[
                {required:true,message:"密码不可为空",tigger:"blur"}
              ]
            },

            //对话框显示和隐藏
            dialogVisible:false
          }
      },
      methods:{
          onSubmit(formName){
            //为表单绑定验证功能
            this.$refs[formName].validate((valid)=>{
              if(valid){
                //使用vue-router路由到指定界面,该方式称为编程式导航
                this.$router.push('/main');
              }else{
                this.dialogVisible=true;
                return false;
              }
            });
          }
      }
    }
</script>

<style lang="scss" scoped>
  .login-box{
    border:1px solid #DCDFE6;
    width: 350px;
    margin:180px auto;
    padding: 35px 35px 15px 35px;
    border-radius: 5px;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    box-shadow: 0 0 25px #909399;
  }
  .login-title{
    text-align:center;
    margin: 0 auto 40px auto;
    color: #303133;
  }
</style>
  • 在router目录下创建一个名为index.js的vue-router路由配置文件
//导入vue
import Vue from 'vue';
import VueRouter from 'vue-router';
//导入组件
import Main from "../views/Main";
import Login from "../views/Login";
//使用
Vue.use(VueRouter);
//导出
export default new VueRouter({
  routes: [
    {
      //登录页
      path: '/main',
      component: Main
    },
    //首页
    {
      path: '/login',
      component: Login
    },
  ]

})
  • 编写 APP.vue
<template>
  <div id="app">
    <router-view></router-view>
  </div>
</template>

<script>


    export default {
        name: 'App',

    }
</script>

<style>
  #app {
    font-family: 'Avenir', Helvetica, Arial, sans-serif;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
    text-align: center;
    color: #2c3e50;
    margin-top: 60px;
  }
</style>
  • 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'

Vue.config.productionTip = false

Vue.use(router)
Vue.use(ElementUI)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  render:h=>h(App)
})
  • 测试npm run dev

说明: 如果出现错误: 可能是因为sass-loader的版本过高导致的编译错误 ,可以去package.json文件中把sass-loder的版本降低,也有可能是node-sass版本过高,看报错内容修改相应的版本

路由嵌套

嵌套路由又称子路由,在实际应用中,通常由多层嵌套的组件组合而成

  • 创建用户信息组件,在 views/user 目录下创建一个名为 Profile.vue 的视图组件
<template>
  <h1>个人信息</h1>
</template>
<script>
  export default {
    name: "UserProfile"
  }
</script>
<style scoped>
</style>
  • 在用户列表组件在 views/user 目录下创建一个名为 List.vue 的视图组件
<template>
  <h1>用户列表</h1>
</template>
<script>
  export default {
    name: "UserList"
  }
</script>
<style scoped>
</style>
  • 修改首页视图,我们修改 Main.vue 视图组件,此处使用了 ElementUI 布局容器组件
<template>
    <div>
      <el-container>
        <el-aside width="200px">
          <el-menu :default-openeds="['1']">
            <el-submenu index="1">
              <template slot="title"><i class="el-icon-caret-right"></i>用户管理</template>
              <el-menu-item-group>
                <el-menu-item index="1-1">
                <!--插入的地方-->
                  <router-link to="/user/profile">个人信息</router-link>
                </el-menu-item>
                <el-menu-item index="1-2">
                <!--插入的地方-->
                  <router-link to="/user/list">用户列表</router-link>
                </el-menu-item>
              </el-menu-item-group>
            </el-submenu>
            <el-submenu index="2">
              <template slot="title"><i class="el-icon-caret-right"></i>内容管理</template>
              <el-menu-item-group>
                <el-menu-item index="2-1">分类管理</el-menu-item>
                <el-menu-item index="2-2">内容列表</el-menu-item>
              </el-menu-item-group>
            </el-submenu>
          </el-menu>
        </el-aside>

        <el-container>
          <el-header style="text-align: right; font-size: 12px">
            <el-dropdown>
              <i class="el-icon-setting" style="margin-right: 15px"></i>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>个人信息</el-dropdown-item>
                <el-dropdown-item>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-header>
          <el-main>
          <!--在这里展示视图-->
            <router-view />
          </el-main>
        </el-container>
      </el-container>
    </div>
</template>
<script>
    export default {
        name: "Main"
    }
</script>
<style scoped lang="scss">
  .el-header {
    background-color: #B3C0D1;
    color: #333;
    line-height: 60px;
  }
  .el-aside {
    color: #333;
  }
</style>
  • 添加了组件,去router修改配置文件
//导入vue
import Vue from 'vue';
import VueRouter from 'vue-router';
//导入组件
import Main from "../views/Main";
import Login from "../views/Login";
//导入子模块
import UserList from "../views/user/List";
import UserProfile from "../views/user/Profile";

//使用
Vue.use(VueRouter);
//导出
export default new VueRouter({
  routes: [
    {
      //登录页
      path: '/main',
      component: Main,
      //  写入子模块
      children: [
        {
          path: '/user/profile',
          component: UserProfile,
        }, {
          path: '/user/list',
          component: UserList,
        },
      ]
    },
    //首页
    {
      path: '/login',
      component: Login

    },
  ]
})

参数传递和重定向

参数传递

  • 修改路由配置, 主要是router下的index.js中的 path 属性中增加了 :id 这样的占位符
{
	path: '/user/profile/:id', 
	name:'UserProfile', 
	component: UserProfile
}

  • 视图层传递参数
<!--name是组件的名字 params是传的参数 如果要传参数的话就需要用v:bind:来绑定-->
<router-link :to="{name:'UserProfile',params:{id:1}}">个人信息</router-link>

说明: 此时我们在Main.vue中的route-link位置处 to 改为了 :to,是为了将这一属性当成对象使用,注意 router-link 中的 name 属性名称 一定要和 路由中的 name 属性名称 匹配,因为这样 Vue 才能找到对应的路由路径

  • 接收参数
<template>
  <!--  所有的元素必须在根节点下-->
  <div>
    <h1>个人信息</h1>
    {{$route.params.id}}
  </div>
</template>

说明:所有的元素必须在根节点下面,否则会报错

使用props 减少耦合

  • 修改路由配置 , 主要在router下的index.js中的路由属性中增加了 props: true 属性
{
	path: '/user/profile/:id', 
	name:'UserProfile', 
	component: UserProfile, 
	props: true
}

  • 传递参数和之前一样
  • 在Profile.vue接收参数为目标组件增加 props 属性
<template>
  <div>
    个人信息
    {{ id }}
  </div>
</template>
<script>
    export default {
      props: ['id'],
      name: "UserProfile"
    }
</script>
<style scoped>
</style>

重定向

Vue 中的重定向是作用在路径不同但组件相同的情况

  • 在router/index.js配置重定向路径
{
  path: '/main',
  name: 'Main',
  component: Main
},
{
  path: '/goHome',
  redirect: '/main'
}

  • 视图增加
<el-menu-item index="1-3">
    <!--插入的地方-->
    <router-link to="/goHome">返回首页</router-link>
</el-menu-item>

路由模式、404和路由钩子

路由模式

路由模式有两种

  • hash:路径带 # 符号,如 http://localhost/#/login
  • history:路径不带 # 符号,如 http://localhost/login

修改路由配置

export default new VueRouter({
  mode:'history',
  routes: []
  )}

在路由的配置中修改

404页面

  • 创建一个NotFound.vue视图
<template>
  <div>
    <h1>404,你的页面走丢了</h1>
  </div>
</template>
<script>
    export default {
        name: "NotFound"
    }
</script>
<style scoped>
</style>

  • 修改路由配置index.js
import NotFound from '../views/NotFound'
{
   path: '*',
   component: NotFound
}

路由钩子

除了之前的钩子函数还存在两个钩子函数

beforeRouteEnter:在进入路由前执行
beforeRouteLeave:在离开路由前执行

  • 在 Profile.vue 使用
<script>
    export default {
        name: "UserProfile",
        beforeRouteEnter: (to, from, next) => {
            console.log("准备进入个人信息页");
            next();
        },
        beforeRouteLeave: (to, from, next) => {
            console.log("准备离开个人信息页");
            next();
        }
    }
</script>
参数说明:

to:路由将要跳转的路径信息

from:路径跳转前的路径信息
next:路由的控制参数
next() 跳入下一个页面
next(’/path’) 改变路由的跳转方向,使其跳到另一个路由
next(false) 返回原来的页面
next((vm)=>{}) 仅在 beforeRouteEnter 中可用,vm 是组件实例

在钩子函数中进行异步请求

  • 安装Axios

cnpm install --save vue-axios

  • main.js引用 Axios
import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios)

{
  "name": "cv战士",
  "url": "https://blog.csdn/qq_45408390?spm=1001.2101.3001.5343",
  "page": 1,
  "isNonProfit": true,
  "address": {
    "street": "含光门",
    "city": "陕西西安",
    "country": "中国"
  },
  "links": [
    {
      "name": "bilibili",
      "url": "https://bilibili"
    },
    {
      "name": "cv战士",
      "url": "https://blog.csdn/qq_45408390?spm=1001.2101.3001.5343"
    },
    {
      "name": "百度",
      "url": "https://www.baidu/"
    }
  ]
}

说明: 只有我们的 static 目录下的文件是可以被访问到的,所以我们就把静态文件放入该目录下

  • 在 beforeRouteEnter 中进行异步请求
<script>
    export default {
        name: "UserProfile",
        beforeRouteEnter: (to, from, next) => {
            console.log("准备进入个人信息页");
            next(vm => {
                //进入路由之前执行getData方法
                vm.getData()
            });
        },
        beforeRouteLeave: (to, from, next) => {
            console.log("准备离开个人信息页");
            next();
        },
        //axios
        methods: {
            getData: function () {
                this.axios({
                    method: 'get',
                    url: 'http://localhost:8080/static/mock/data.json'
                }).then(function (response) {
                    console.log(response)
                })
            }
        }
    }
</script>

到此就结束了,再次声明,此文,只作本人复习使用。如有侵权,请联系我,将妥善处理。

邮箱:719167291@qq

更多推荐

基于《狂神说Java》Vue--学习笔记

本文发布于:2023-04-29 21:23:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/0595bc26c9cf9293e3b018ce77210a68.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:学习笔记   狂神说   Java   Vue

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 112309文章数
  • 28572阅读数
  • 0评论数