vue笔记

1. VueJS 概述

1.1 VueJS介绍

Vue.js是一个构建数据驱动的 web 界面的渐进式框架。Vue.js 的目标是通过尽可能简单的 API 实现响应的数据绑定和组合的视图组件。它不仅易于上手,还便于与第三方库或既有项目整合。
官网:https://cn.vuejs.org/

1.2 MVVM模式

MVVM是Model-View-ViewModel的简写。它本质上就是MVC 的改进版。MVVM 就是将其中的View 的状态和行为抽象化,让我们将视图 UI 和业务逻辑分开MVVM模式和MVC模式一样,主要目的是分离视图(View)和模型(Model)
Vue.js 是一个提供了 MVVM 风格的双向数据绑定的 Javascript 库,专注于View 层。它的核心是 MVVM 中的 VM,也就是 ViewModel。 ViewModel负责连接 View 和 Model,保证视图和数据的一致性,这种轻量级的架构让前端开发更加高效、便捷
在这里插入图片描述

2. Vue.js快速入门

2.1 入门程序

我们使用vue编写一个最简单的入门程序:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>快速入门</title>
    <script src="js/vuejs-2.5.16.js"></script>
</head>
<body>
    <div id="app">
        {{message}}
    </div>
    <script>
        new Vue({
           el:"#app",   //表示当前vue对象接管了div区域
           data:{
               message:"hello vue!"     //注意结尾不要写分号
           }
        });
    </script>
</body>
</html>

效果图:
在这里插入图片描述

2.2 插值表达式

数据绑定最常见的形式就是使用“Mustache”语法 (双大括号) 的文本插值,Mustache 标签将会被替代为对应数据对象上属性的值。无论何时,绑定的数据对象上属性发生了改变,插值处的内容都会更新。
Vue.js 都提供了完全的 JavaScript 表达式支持。
例如:

{{ number + 1 }} 
{{ ok ? 'YES' : 'NO' }}

这些表达式会在所属 Vue 实例的数据作用域下作为 JavaScript 被解析。有个限制就是,每个绑定都只能包含单个表达式,所以下面的例子都不会生效。

<!-- 这是语句,不是表达式 -->
{{ var a = 1 }}
<!-- 流控制也不会生效,请使用三元表达式 -->
{{ if (ok) { return message } }}

3. VueJs常用指令

3.1 事件处理

3.1.1 事件绑定指令v-on

可以“v-on”指令监听 DOM 事件,并在触发时运行一些动作。使用时以“v-on”作为属性前缀,后面跟上要处理的事件名称,属性的值就是我们事件的处理方法。

3.1.1.1绑定单击事件

使用方法:v-on:click=“onClick()”
例如:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vuejs-2.5.16.js"></script>
</head>
<body>
    <div id="app">
        <span>
            {{message}}
        </span>
        <br>
        <input type="button" value="clickme" v-on:click="sayHello()">
    </div>
    <script>
        new Vue({
            el:"#app",
            data:{
                message:""
            },
            methods:{
                sayHello:function() {
                    this.message = "hello vue!";
                }
            }
        });
    </script>
</body>
</html>

效果图:
在这里插入图片描述
点击“clickme”按钮在页面上显示“hello vue!”

3.1.1.2 绑定键盘按下事件

使用方法:v-on:keydown=“onKeyDown()”
例如:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vuejs-2.5.16.js"></script>
</head>
<body>
    <div id="app">
        <span>
            {{message}}
        </span>
        <br>
        <input type="text" v-on:keydown="onKeyDown($event)">
    </div>
    <script>
        new Vue({
            el:"#app",
            data:{
                message:""
            },
            methods:{
                onKeyDown:function(event) {
                    //如果按下的是回车键
                    //键盘上每个键都对应一个编号就是keycode,回车键的keycode是13
                    if (event.keyCode == 13) {
                        this.message = "hello vue!";
                    }
                }
            }
        });
    </script>
</body>
</html>

效果图:
在这里插入图片描述
在文本框这按下回车键,页面上显示“hello vue!”

3.1.1.3 绑定鼠标移动事件

使用方法:
v-on:mousemove=“onMouseMove($event)”
例如:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vuejs-2.5.16.js"></script>
</head>
<body>
    <div id="app">
        <div style="height: 300px;width: 100%;background-color: dodgerblue" v-on:mousemove="onMouseMove($event)">
            X:{{x}}
            <br>
            Y:{{y}}
        </div>
        <br>
    </div>
    <script>
        new Vue({
            el:"#app",
            data:{
                x:0,
                y:0
            },
            methods:{
                onMouseMove:function(event) {
                    //鼠标每移动一个位置就会触发一次mousemove事件
                    //在此事件这可以取到鼠标的坐标
                    this.x = event.x;
                    this.y = event.y;
                }
            }
        });
    </script>
</body>
</html>

运行效果:
在这里插入图片描述

3.1.2 事件修饰符

在事件处理程序中调用 event.preventDefault() 或 event.stopPropagation() 是非常常见的需求。尽管我们可以在 methods 中轻松实现这点,但更好的方式是:methods 只有纯粹的数据逻辑,而不是去处理 DOM 事件细节。
为了解决这个问题, Vue.js 为 v-on 提供了 事件修饰符。通过由点(.)表示的指令后缀来调用修饰符。
我们先看一个阻止表单提交的例子:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vuejs-2.5.16.js"></script>
</head>
<body>
    <div id="app">
        <form action="http://bbs.itheima.com/search.php" method="get" v-on:submit="onSubmit($event)">
            <input type="hidden" name="searchid" value="162">
            <input type="hidden" name="searchsubmit" value="yes">
            <input type="text" name="kw">
            <input type="submit" value="搜索">
        </form>

    </div>
    <script>
        new Vue({
            el:"#app",
            data:{
                x:0,
                y:0
            },
            methods:{
                onSubmit:function(event) {
                    //禁止表单默认提交行为
                    event.preventDefault();
                }
            }
        });
    </script>
</body>
</html>

上面的代码这,在submit事件中调用了“event.preventDefault()”方法阻止了表单的默认提交行为。如果使用事件修饰符可以简化为以下写法:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vuejs-2.5.16.js"></script>
</head>
<body>
    <div id="app">
        <form action="http://bbs.itheima.com/search.php" method="get" v-on:submit.prevent>
            <input type="hidden" name="searchid" value="162">
            <input type="hidden" name="searchsubmit" value="yes">
            <input type="text" name="kw">
            <input type="submit" value="搜索">
        </form>

    </div>
    <script>
        new Vue({
            el:"#app",
            data:{
                x:0,
                y:0
            },
            methods:{
                /*onSubmit:function(event) {
                    //禁止表单默认提交行为
                    event.preventDefault();
                }*/
            }
        });
    </script>
</body>
</html>

只需要事件修饰符就可以达到上面的效果,不需要定义事件的处理方法。
常用的事件修饰符:

.stop 			:阻止事件冒泡
.prevent 			:阻止事件的默认行为
.capture 			:使用事件捕获模式
.self				:只当事件在该元素本身(而不是子元素)触发时触发

3.1.3 按键修饰符

在监听键盘事件时,我们经常需要监测常见的键值。 Vue 允许为 v-on 在监听键盘事件时添加按键修饰符,例如当判断是否是回车键按下时就可以写成:

<input type="text" name="keyword" v-on:keydown.enter="enterKeyDown()">

全部的按键别名:
.enter
.tab
.delete (捕获 “删除” 和 “退格” 键)
.esc
.space
.up
.down
.left
.right

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vuejs-2.5.16.js"></script>
</head>
<body>
    <div id="app">
        <input type="text" name="keyword" v-on:keydown.enter="enterKeyDown()">
    </div>
    <script>
        new Vue({
            el:"#app",
            methods:{
                enterKeyDown:function () {
                    alert("hello");
                }
            }
        });
    </script>
</body>
</html>

3.1.4 v-on简写方式

在编码过程中,如果觉得写“v-on:事件名称”这种方式很繁琐的话,可以使用“@事件名称”这种方式,例如:

<!-- 完整语法 -->
<a v-on:click="doSomething">...</a>
<!-- 缩写 -->
<a @click="doSomething">...</a>

<!-- 完整语法 -->
<input v-on:keyup.enter="submit">
<!-- 缩写语法 -->
<input @keyup.enter="submit">

3.2 页面数据绑定

3.2.1 插值表达式

我们可以使用插值表达式“{{val}}”将变量的值输出到页面。上面已经介绍过,不再赘述。

3.2.2 v-text

v-text指令可以将变量的值原封不动的显示到页面的标签内部

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vuejs-2.5.16.js"></script>
</head>
<body>
    <div id="app">

        <div>插值形式:{{message}}</div>
        <hr>
        <label>v-text形式:</label>
        <div v-text="message"></div>
    </div>
    <script>
        new Vue({
            el:"#app",
            data:{
                message:"<h1>传智播客</h1>"
            }
        });
    </script>
</body>
</html>

在这里插入图片描述

3.2.3 v-html

v-html指令可以将变量的值以html格式显示到页面,和v-text不同的是,如果变量这的内容有html标签,那么就会将html解析。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vuejs-2.5.16.js"></script>
</head>
<body>
    <div id="app">

        <div>插值形式:{{message}}</div>
        <hr>
        <label>v-text形式:</label>
        <div v-text="message"></div>
        <label>v-html形式:</label>
        <div v-html="message"></div>
    </div>
    <script>
        new Vue({
            el:"#app",
            data:{
                message:"<h1>传智播客</h1>"
            }
        });
    </script>
</body>
</html>

在这里插入图片描述

3.3 属性与变量绑定指令

3.3.1 变量绑定到属性值

插值语法不能作用在 HTML 属性上,遇到这种情况应该使用 v-bind指令

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vuejs-2.5.16.js"></script>
</head>
<body>
    <div id="app">
        <input type="text" v-bind:value="message">
        <button @click="changeRed()">red</button>
        <button @click="changeGreen()">green</button>
    </div>
    <script>
        new Vue({
            el:"#app",
            data:{
                message:"black"
            },
            methods:{
                changeRed:function () {
                    this.message = "red";
                },
                changeGreen:function () {
                    this.message = "green";
                }
            }
        });
    </script>
</body>
</html>

v-bind简写方式

<!-- 完整语法 -->
<a v-bind:href="url">...</a>
<!-- 缩写 -->
<a :href="url">...</a>

3.3.2 数据的双向绑定

v-bind只能将变量的值绑定到属性上,当属性发生变化后,并不能改变变量的值,如果想实现修改文本框中的内容,对应的变量的值也随之发生变化,那么就需要使用v-model指令,可以实现数据的双向绑定,不要同时使用v-bind和v-model会冲突。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vuejs-2.5.16.js"></script>
</head>
<body>
    <div id="app">
        <input type="text" v-model="message">
        <button @click="changeRed()">red</button>
        <button @click="changeGreen()">green</button>
        <button @click="showColor()">showColorValue</button>
    </div>
    <script>
        new Vue({
            el:"#app",
            data:{
                message:"black"
            },
            methods:{
                changeRed:function () {
                    this.message = "red";
                },
                changeGreen:function () {
                    this.message = "green";
                },
                showColor:function () {
                    alert(this.message)
                }
            }
        });
    </script>
</body>
</html>

v-bind属性就可以将一个表单的数据绑定到一个对象的属性上,例如:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>v-model</title>
    <script src="js/vuejs-2.5.16.js"></script>
</head>
<body>
<div id="app">
    姓名:<input type="text" id="username" v-model="user.username"><br>
    密码:<input type="password" id="password" v-model="user.password"><br>
    <input type="button" @click="fun" value="获取">
</div>
<script>
    new Vue({
        el:'#app', //表示当前vue对象接管了div区域
        data:{
            user:{username:"",password:""}
        },
        methods:{
            fun:function(){
                alert(this.user.username+"   "+this.user.password);
                this.user.username="tom";
                this.user.password="11111111";
            }
        }
    });
</script>
</body>
</html>

3.4 集合操作指令

在处理页面的过程中,免不了要处理集合数据,例如在页面展示数组或者是list信息,此时就可以使用v-for指令来将集合中的数据展示出来。
使用方法:
在迭代的标签的属性上添加v-for:

<li v-for="var in collection">{{var}}</li>

3.4.1 遍历数组

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>v-model</title>
    <script src="js/vuejs-2.5.16.js"></script>
</head>
<body>
<div id="app">
    <ul>
        <li v-for="(item,index) in list">{{item+"  "+index}}</li>
    </ul>
</div>
<script>
    new Vue({
        el:'#app', //表示当前vue对象接管了div区域
        data:{
            list:[1,2,3,4,5,6]
        }
    });
</script>
</body>
</html>

3.4.2 遍历对象

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>v-for示例1</title>
    <script src="js/vuejs-2.5.16.js"></script>
</head>
<body>
<div id="app">
    <ul>
        <li v-for="(value,key) in product">{{key}}--{{value}}</li>
    </ul>
</div>
<script>
    new Vue({
        el:'#app', //表示当前vue对象接管了div区域
        data:{
            product:{id:1,pname:"电视机",price:6000}
        }
    });
</script>
</body>
</html>

3.4.3 变量对象数组

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>v-for示例1</title>
    <script src="js/vuejs-2.5.16.js"></script>
</head>
<body>
<div id="app">
    <table border="1">
        <tr>
            <td>序号</td>
            <td>名称</td>
            <td>价格</td>
        </tr>
        <tr v-for="p in products">
            <td>
                {{p.id}}
            </td>
            <td>
                {{p.pname}}
            </td>
            <td>
                {{p.price}}
            </td>
        </tr>
    </table>
</div>
<script>
    new Vue({
        el:'#app', //表示当前vue对象接管了div区域
        data:{
            products:[{id:1,pname:"电视机",price:6000},{id:2,pname:"电冰箱",price:8000},
                {id:3,pname:"电风扇",price:600}]
        }
    });
</script>
</body>
</html>

3.5 判断元素显示指令

v-if与v-show两个指令都可以根据变量的值来决定元素是否显示。
v-if是根据表达式的值来决定是否渲染元素
v-show是根据表达式的值来切换元素的display css属性

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>v-if与v-show</title>
    <script src="js/vuejs-2.5.16.js"></script>
</head>
<body>
<div id="app">
    <span v-if="flag">传智播客</span><br>
    <span v-show="flag">itcast</span><br>
    <button @click="toggle">切换</button>
</div>
<script>
    new Vue({
        el:'#app', //表示当前vue对象接管了div区域
        data:{
            flag:true
        },
        methods:{
            toggle:function(){
                this.flag=!this.flag;
            }
        }
    });
</script>
</body>
</html>

4. VueJS生命周期

每个 Vue 实例在被创建之前都要经过一系列的初始化过程。
在这里插入图片描述
vue在生命周期中有这些状态,
beforeCreate,created,beforeMount,mounted,beforeUpdate,updated,beforeDestroy,destroyed。Vue
在实例化的过程中,会调用这些生命周期的钩子,给我们提供了执行自定义逻辑的机会。那么,在这些vue钩子中,vue实例到底执行了那些操作,我们先看下面执行的例子:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>生命周期</title>
    <script src="js/vuejs-2.5.16.js"></script>
</head>

<body>
<div id="app">
    {{message}}
</div>

<script>
    var vm = new Vue({
        el: "#app",
        data: {
            message: 'hello world'
        },
        beforeCreate: function() {
            console.log(this);
            showData('创建vue实例前', this);
        },
        created: function() {
            showData('创建vue实例后', this);
        },
        beforeMount: function() {
            showData('挂载到dom前', this);
        },
        mounted: function() {
            showData('挂载到dom后', this);
        },
        beforeUpdate: function() {
            showData('数据变化更新前', this);
        },
        updated: function() {
            showData('数据变化更新后', this);
        },
        beforeDestroy: function() {
            vm.test = "3333";
            showData('vue实例销毁前', this);
        },
        destroyed: function() {
            showData('vue实例销毁后', this);
        }

    });

    function realDom() {
        console.log('真实dom结构:' + document.getElementById('app').innerHTML);
    }

    function showData(process, obj) {
        console.log(process);
        console.log('data 数据:' + obj.message)
        console.log('挂载的对象:')
        console.log(obj.$el)
        realDom();
        console.log('------------------')
        console.log('------------------')
    }
    vm.message="good...";
    vm.$destroy();
</script>
</body>
</html>

vue对象初始化过程中,会执行到beforeCreate,created,beforeMount,mounted 这几个钩子的内容:

  • beforeCreate :数据还没有监听,没有绑定到vue对象实例,同时也没有挂载对象
  • created :数据已经绑定到了对象实例,但是还没有挂载对象
  • beforeMount: 模板已经编译好了,根据数据和模板已经生成了对应的元素对象,将数据对象关联到了对象的 el属性,el属性是一个HTMLElement对象,也就是这个阶段,vue实例通过原生的createElement等方法来创建这个html片段,准备注入到我们vue实例指明的el属性所对应的挂载点
  • mounted:将el的内容挂载到了el,相当于我们在jquery执行了(el).html(el),生成页面上真正的dom,上面我们就会发现dom的元素和我们el的元素是一致的。在此之后,我们能够用方法来获取到el元素下的dom对象,并进行各种操作
  • 当我们的data发生改变时,会调用beforeUpdate和updated方
  • beforeUpdate :数据更新到dom之前,我们可以看到$el对象已经修改,但是我们页面上dom的数据还没有发生改变
  • updated: dom结构会通过虚拟dom的原则,找到需要更新页面dom结构的 小路径,将改变更新到 dom上面,完成更新
  • beforeDestroy,destroed :实例的销毁,vue实例还是存在的,只是解绑了事件的监听还有watcher对象数据与view的绑定,即数据驱动

5. VueJS ajax

5.1 vue-resource

vue-resource是Vue.js的插件提供了使用XMLHttpRequest或JSONP进行Web请求和处理响应的服务。 当vue更新到2.0之后,作者就宣告不再对vue-resource更新,而是推荐的axios,在这里大家了解一下vue-resource就可以。
vue-resource的github: https://github.com/pagekit/vue-resource

5.2 Axios

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中
axios的github:
https://github.com/axios/axios

5.2.1 引入axios

首先就是引入axios,如果你使用es6,只需要安装axios模块之后

import axios from 'axios';
//安装方法
npm install axios
//或
bower install axios

当然也可以用script引入:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

5.2.2 get请求

//通过给定的ID来发送请求
axios.get('/user?ID=12345')
    .then(function(response){
        console.log(response);
    })
    .catch(function(err){
        console.log(err);
    });
//以上请求也可以通过这种方式来发送
axios.get('/user',{
        params:{
            ID:12345
        }
    })
    .then(function(response){
        console.log(response);
    })
    .catch(function(err){
        console.log(err);
    });

5.2.3 Post请求

axios.post('/user',{
        firstName:'Fred',
        lastName:'Flintstone'
    })
    .then(function(res){
        console.log(res);
    })
    .catch(function(err){
        console.log(err);
    });

为方便起见,为所有支持的请求方法提供了别名
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

6. 综合案例

6.1 需求

完成用户的查询与修改操作

6.2 数据库

CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `age` int(11) DEFAULT NULL,
  `username` varchar(20) DEFAULT NULL,
  `PASSWORD` varchar(50) DEFAULT NULL,
  `email` varchar(50) DEFAULT NULL,
  `sex` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

可以直接使用参考资料这的sql脚本创建数据库。

6.3 Pom文件

<?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>com.itheima</groupId>
    <artifactId>vue-project</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <properties>
        <spring.version>4.2.4.RELEASE</spring.version>
        <hibernate.version>5.0.7.Final</hibernate.version>
        <slf4j.version>1.6.6</slf4j.version>
        <log4j.version>1.2.12</log4j.version>
        <c3p0.version>0.9.1.2</c3p0.version>
        <mysql.version>5.1.6</mysql.version>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>

    <dependencies>
        <!-- junit单元测试 -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!-- spring beg -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.6.8</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>


        <!-- spring end -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.5</version>
        </dependency>

        <!-- hibernate beg -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>5.2.1.Final</version>
        </dependency>
        <!-- hibernate end -->

        <!-- c3p0 beg -->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>${c3p0.version}</version>
        </dependency>
        <!-- c3p0 end -->

        <!-- log end -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>${log4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <!-- log end -->


        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>1.9.0.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.2.4.RELEASE</version>
        </dependency>

        <!-- el beg 使用spring data jpa 必须引入 -->
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>2.2.4</version>
        </dependency>

        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.el</artifactId>
            <version>2.2.4</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <version>2.2</version>
                <configuration>
                    <path>/</path>
                    <port>8080</port>
                </configuration>
            </plugin>
        </plugins>
    </build>
    
</project>

6.4 applicationContext.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:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:task="http://www.springframework.org/schema/task"
       xsi:schemaLocation="
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
      http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
      http://www.springframework.org/schema/data/jpa
      http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
    <!-- 1.dataSource 配置数据库连接池-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/vuedb" />
        <property name="user" value="root" />
        <property name="password" value="root" />
    </bean>
    <!--2.工厂类对象-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan" value="com.itheima.vue.entity"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true"/>
                <property name="generateDdl" value="true"/>
            </bean>
        </property>
    </bean>
    <!-- 3.1JPA事务管理器  -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>
    <!-- 3.2.txAdvice-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="save*" propagation="REQUIRED"/>
            <tx:method name="insert*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="delete*" propagation="REQUIRED"/>
            <tx:method name="get*" read-only="true"/>
            <tx:method name="find*" read-only="true"/>
            <tx:method name="*" propagation="REQUIRED"/>
        </tx:attributes>
    </tx:advice>
    <!-- 3.3.aop-->
    <aop:config>
        <aop:pointcut id="pointcut" expression="execution(* com.itheima.vue.service.*.*(..))" />
        <aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
    </aop:config>
    <!--4.dao包扫描器-->
    <jpa:repositories base-package="com.itheima.vue.dao"
                      transaction-manager-ref="transactionManager" entity-manager-factory-ref="entityManagerFactory"/>
    <context:component-scan base-package="com.itheima.vue.service"/>
</beans>

6.5 Springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 配置创建 spring 容器要扫描的包 -->
    <context:component-scan base-package="com.itheima.vue.controller"/>
    <mvc:annotation-driven/>
</beans>

6.6 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_3_1.xsd"
         version="3.1"
         metadata-complete="true">
  <!-- 手动指定 spring 配置文件位置 -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!-- 配置 spring 提供的监听器,用于启动服务时加载容器 。
该间监听器只能加载 WEB-INF 目录中名称为 applicationContext.xml 的配置文件 -->
  <listener>
    <listener-class>
      org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>
  <!-- 配置 spring mvc 的核心控制器 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 配置初始化参数,用于读取 springmvc 的配置文件 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!-- 配置 servlet 的对象的创建时间点:应用加载时创建。取值只能是非 0 正整数,表示启动顺
    序 -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <!-- 配置 springMVC 编码过滤器 -->
  <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>
    <!-- 启动过滤器 -->
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <!-- 过滤所有请求 -->
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>user.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
</web-app>

6.7 User.js

var vue = new Vue({
    el: "#app",
    data: {
        user: {id:"",username:"aaa",password:"",age:"",sex:"",email:""},
        userList: []
    },
    methods: {
        findAll: function () {
            var _this = this;
            axios.get("/vuejsDemo/user/findAll.do").then(function (response) {
                _this.userList = response.data;
                console.log(_this.userList);
            }).catch(function (err) {
                console.log(err);
            });
        },
        findById: function (userid) {
            var _this = this;
            axios.get("/vuejsDemo/user/findById.do", {
                params: {
                    id: userid
                }
            }).then(function (response) {
              _this.user = response.data;
                $('#myModal').modal("show");
            }).catch(function (err) {
            });

        },
        update: function (user) {
            var _this = this;
            axios.post("/vuejsDemo/user/update.do",_this.user).then(function (response) {
                _this.findAll();
            }).catch(function (err) {
            });
        }
    },
    created:function(){
        this.findAll();
    }
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值