一,Vue 的demo
1.创建一个web+ maven工程archtype_webapp
2.创建js文件夹,加入js文件,在html中引入
<script src="js/vuejs-2.5.16.js"></script>
<body>
<div id="app">
{{message+"大大"}}<!--插值表达式-->
</div>
</body>
<script>
//view model
new Vue({
el :"#app",//注意这里代表的是让el接管id为APP的区域
data :{
message :"你好,Vue"//注意没有符号
}
});
</script>
3.{{message+“大大”}}
可以使用三元运算符
{{message ? “aaa” : “bbb”}}
不能绑定赋值表达式和多个语句
二v-on用于监听dom事件 (v-on:事件名称 @事件名称)
1.v-on:click的使用
v-on:click = "fun1"
new Vue({
el : "#app",
methods : {
fun1: function () {
alert("我胡汉三又回来了!")
}
}
});
带参数
<div id="app">
{{message}} <br>
<button v-on:click = "fun1('huhuhu')">vue的onclick</button>
</div>
</body>
<script>
//view model
new Vue({
el : "#app",
data : {
message : "aaaa"
},
methods : {
fun1: function (data) {
alert("我胡汉三又回来了!")
this.message = data ;
}
}
});
- v-on:keydown的使用 键盘按下时触发的事件
v-on:keydown=“fun($event)” - (1)传统js的方式实现
<div id="app" align="center">
<!--<div @mouseover="fun1" id="div">
<textarea @mouseover="fun2($event)">这是一个文件域</textarea>
</div>-->
<div onmousemove="f1()" id="div">
<textarea onmousemove="t1()">这是一个文件域</textarea>
</div>
</div>
function f1() {
alert("鼠标来到文件域1");
}
function t1() {
alert("鼠标来到文件域2");
//我们发现文件域也是在div中的,所以触发文件域的方法,也会触发div的方法,所以我们使用这个方法来截断div的方法
event.stopPropagation();
/*该方法将停止事件的传播,阻止它被分派到其他 Document 节点。在事件传播的任何阶段都可以调用它。
注意,虽然该方法不能阻止同一个 Document 节点上的其他事件句柄被调用,但是它可以阻止把事件分派到其他节点。*/
}
(2)Vue的方式实现
<!--@mouseover就相当于v-on:mouseover-->
<div @mouseover="fun1" id="div">
<textarea @mouseover="fun2($event)">这是一个文件域</textarea>
</div>
new Vue({
el:"#app",
methods:{
fun1:function () {
alert("鼠标在div上");
},
fun2:function (event) {
alert("鼠标在文件域上");
event.stopPropagation();
}
}
});
4.事件修饰符
@事件名称.prevent阻止默认事件的执行 @事件名称.stop 阻止事件的传播
(1)传统的js方式实现表单的提交(或截断提交)
<form method="post" action="https://blog.csdn.net/mingxu_W" onclick="return checkForm()">
<input type="submit" value="提交"/>
</form>
function checkForm() {
/*
想要阻止表单提交必须使函数有一个明确的boolean类型的返回值
并且要在调用的时候使用 return 函数名称
* */
return false;//截断提交
//return true;//提交
}
(2)Vue的方式实现表单的提交(或截断提交)
<!--@事件名称.prevent阻止默认事件的执行 @事件名称.stop 阻止事件的传播-->
<form @submit.prevent method="post" action="https://blog.csdn.net/mingxu_W" >
<input type="submit" value="提交"/>
</form>
new Vue({
el:"#app",
});
附加:按键修饰符
Vue 允许为 v-on 在监听键盘事件时添加按键修饰符全部的按键别名:
.enter
.tab
.delete (捕获 "删除" 和 "退格" 键)
.esc
.space
.up
.down
.left
.right
.ctrl
.alt
.shift
.meta
<div id="app">
<input type="text" @keyup.tab="fun1">
</div>
</body>
<script>
//view model
new Vue({
el:'#app',//表示当前vue对象接管了div区域
methods:{
fun1:function(){
alert("你按了tab");
}
}
});
5.v-bind,v-text与v-html
v-html document.getElementByID(“ID”).innerHTML=“html表达式”; 可以解析HTML表达式
v-text document.getElementByID(“ID”).innerText=“html表达式”; 不会解析HTML,但是会显示纯文本
v-bind 插值语法不能作用在 HTML 特性上,遇到这种情况应该使用 v-bind指令
v-text与v-html:
<div id="app">
<div v-text ="message"></div>
<div v-html = "message"></div>
</div>
<script>
//view model
new Vue({
el:"#app",
data:{
message:"<h1>北京</h1>"
}
});
v-bind:插值表达式不能用于HTML的属性取值
<div id="app">
<font size="5" v-bind:color="ys1">传智播客</font>
<font size="5" :color="ys2">黑马程序员</font> <hr>
<a v-bind={href:"http://www.itcast.cn/index/"+id}>itcast</a>
</div>
<script>
new Vue({
el:'#app', //表示当前vue对象接管了div区域
data:{
ys1:"red",
ys2:"green",
id:1
}
});
v-bind简写方式:
<!-- 完整语法 -->
<a v-bind:href="url">...</a>
<!-- 缩写 -->
<a :href="url">...</a>
6.v-model
<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>
</body>
<script>
//view model
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";
}
}
});
- v-for
(1)操作array
<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>
(2)操作对象
<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>
(3)操作对象数组
<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>
(4) v-if与v-show
v-if是根据表达式的值来决定是否渲染元素
v-show是根据表达式的值来切换元素的display css属性
<div id="app">
<span v-if="flag">传智播客</span>
<span v-show="flag">itcast</span>
<button @click="toggle">切换</button>
</div>
<script>
new Vue({
el:'#app', //表示当前vue对象接管了div区域
data:{flag:false },
methods:{
toggle:function(){
this.flag=!this.flag; }
}
});
</script>
7.VueJS生命周期
每个 Vue 实例在被创建之前都要经过一系列的初始化过程.vue在生命周期中有这些状态,beforeCreate,created,beforeMount,mounted,beforeUpdate,updated,beforeDestroy,destroyed。Vue在实例化的过程中,会调用这些生命周期的钩子,给我们提供了执行自定义逻辑的机会。那么,在这些vue钩子中,vue实例到底执行了那些操作,我们先看下面执行的例子
<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>
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的绑定,即数据驱动
8.Vue中ajax的使用
引入axios,首先就是引入axios,如果你使用es6,只需要安装axios模块之后
(1)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);
});
(2)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]])
测试用例:
(1)数据库表
CREATE DATABASE vuejsdemo; USE vuejsdemo; CREATE TABLE USER( id INT PRIMARY KEY AUTO_INCREMENT, age INT, username VARCHAR(20), PASSWORD VARCHAR(50), email VARCHAR(50), sex VARCHAR(20) )
(2)按照数据库表的字段创建实体类
(3)pom.xml引入依赖
<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>day00_ee41_02vueuser</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.0.2.RELEASE</spring.version>
<slf4j.version>1.6.6</slf4j.version>
<log4j.version>1.2.12</log4j.version>
<mybatis.version>3.4.5</mybatis.version>
</properties>
<dependencies> <!-- spring -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.6.8</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-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<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> <!-- log start -->
<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>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
</dependencies>
</project>
(4)web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name></display-name>
<!-- 手动指定 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>springmvcDispatcherServlet</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>springmvcDispatcherServlet</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>index.htm</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>
(4.2)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">
<!-- 制定扫包规则 ,只扫描使用@Controller 注解的 JAVA 类 -->
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
(5)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:tx="http://www.springframework.org/schema/tx"
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/tx http://www.springframework.org/schema/tx/spring-tx.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">
<!-- 配置 spring 创建容器时要扫描的包 -->
<context:component-scan base-package="com.itheima">
<!--制定扫包规则,不扫描@Controller 注解的 JAVA 类,其他的还是要扫描 -->
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置 MyBatis 的 Session 工厂 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 配置 Mapper 扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.itheima.dao"/>
</bean>
<tx:annotation-driven/>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 配置事务的通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED" read-only="false"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置aop -->
<aop:config>
<aop:pointcut expression="execution(* com.itheima.service.impl.*.*(..))" id="pt1"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="pt1"/>
</aop:config>
</beans>
(6)数据库连接
db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/vuejsDemo
jdbc.username=root
jdbc.password=root
(7)Controller
@RequestMapping("/user")
@Controller
@ResponseBody
public class UserController {
@Autowired
private IUserService userService;
@RequestMapping(value="/findAll.do")
public List<User> findAll() {
return userService.findAll();
}
@RequestMapping(value="/findById.do")
public User findById(Integer id) {
return userService.findById(id);
}
@RequestMapping(value="/update.do")
public User update(@RequestBody User user) {
return userService.update(user);
}
}
(8)dao
@Select("select * from user")
public List<User> findAll();
@Select("select * from user where id=#{id}")
User findById(Integer id);
@Update("update user set username=#{username},password=#{password},sex=#{sex},age=# {age},email=#{email} where id=#{id}")
void update(User user);
(9)service
package com.itheima.service;
import com.itheima.domain.User;
import java.util.List;
/**
* 用户的业务层接口
* @author 黑马程序员
* @Company http://www.ithiema.com
*/
public interface IUserService {
/**
* 查询用户列表
*/
List<User> findAll();
/**
* 根据id查询
* @param userId
* @return
*/
User findById(Integer userId);
/**
* 更新用户
* @param user
*/
void updateUser(User user);
}
(10)impl
package com.itheima.service.impl;
import com.itheima.dao.IUserDao;
import com.itheima.domain.User;
import com.itheima.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class UserServiceImpl implements IUserService {
@Autowired
private IUserDao userDao;
@Override
public List<User> findAll() {
return userDao.findAll();
}
@Override
public User findById(Integer userId) {
return userDao.findById(userId);
}
@Override
public void updateUser(User user) {
userDao.updateUser(user);
}
}