Vue的常用特性
表单操作
- 表单元素
包含 text,radio,checkbox,select,textarea的Vue操作方式,另外提交禁用默认的表单提交方式,采用手动的ajax提交表单数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
form div {
height: 40px;
line-height: 40px;
}
form div:nth-child(4) {
height: auto;
}
form div span:first-child {
display: inline-block;
width: 100px;
}
</style>
</head>
<body>
<div id="app">
<form action="http://www.baidu.com">
<div>
<span>姓名:</span>
<span>
<input type="text" v-model="uname">
</span>
</div>
<div>
<span>性别:</span>
<span>
<input type="radio" id="male" value="1" v-model="gender">
<label for="male">男</label>
<input type="radio" id="female" value="2" v-model="gender">
<label for="female">女</label>
</span>
</div>
<div>
<span>爱好:</span>
<input type="checkbox" id="ball" value="1" v-model="hobby">
<label for="ball">篮球</label>
<input type="checkbox" id="sing" value="2" v-model="hobby">
<label for="sing">唱歌</label>
<input type="checkbox" id="code" value="3" v-model="hobby">
<label for="code">写代码</label>
</div>
<div>
<span>职业:</span>
<select v-model="occupation">
<option value="0">请选择职业...</option>
<option value="1">教师</option>
<option value="2">软件工程师</option>
<option value="3">律师</option>
</select>
</div>
<div>
<span>个人简介:</span>
<textarea v-model="desc"></textarea>
</div>
<div>
<input type="submit" value="提交" v-on:click.prevent="handle">
</div>
</form>
</div>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript">
/*
表单基本操作
*/
var vm = new Vue({
el: '#app',
data: {
uname: "yorick",
gender: 1,
hobby: [1,2],
occupation: 2,
desc: "Hello World"
},
methods: {
handle: function(){
console.log(this.uname);
console.log(this.gender);
console.log(this.hobby.toString());
console.log(this.occupation);
console.log(this.desc);
}
}
});
</script>
</body>
</html>
- 表单域修饰符
1.number:将字符串转换为数值类型
2.trim:去除内容两侧的空格
3.lazy:将input事件转变为change事件(失去焦点时触发)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<input type="text" v-model.number="age">
<input type="text" v-model.trim="info">
<input type="text" v-model.lazy="desc">
<div v-text="desc"></div>
<button v-on:click="handle">提交</button>
</div>
<script src="js/jquery-3.4.1.js"></script>
<script src="js/vue.js"></script>
<script>
var vm = new Vue({
el: "#app",
data: {
age: "",
info: "",
desc: ""
},
methods:{
handle: function(){
console.log(this.age + 10); //数值计算,而并非字符串拼接
console.log(this.info.length); //忽略空格的长度
}
}
});
</script>
</body>
</html>
自定义指令
- 无参数自定义指令定义的语法规则
Vue.directive("focus",{
inserted: function(el){
el.focus();
}
});
- 无参数自定义指令用法
<input type="text" v-focus>
实例:通过自定义指令实现刷新页面后默认光标选中输入框
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<input type="text" v-focus>
</div>
<script src="js/jquery-3.4.1.js"></script>
<script src="js/vue.js"></script>
<script>
Vue.directive("focus",{
inserted: function(el){
el.focus();
}
});
var vm = new Vue({
el: "#app",
data: {
},
methods:{
}
});
</script>
</body>
</html>
- 带参数的自定义指令的语法规则
Vue.directive("color",{
bind: function(el,binding){
el.style.backgroundColor = binding.value.color;
}
});
- 带参数的自定义指令用法
<input type="text" v-color="msg">
实例:通过带参数的自定义指令实现改变输入框的背景颜色
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<input type="text" v-color="msg">
</div>
<script src="js/jquery-3.4.1.js"></script>
<script src="js/vue.js"></script>
<script>
Vue.directive("color",{
bind: function(el,binding){
el.style.backgroundColor = binding.value.color;
}
});
var vm = new Vue({
el: "#app",
data: {
msg:{
color: "blue"
}
},
methods:{
}
});
</script>
</body>
</html>
- 局部自定义指令
将自定义指令放在组件中变为局部指令,而非之前定义的全局指令。可定义多个自定义指令。
directives:{
"focus": {
inserted: function(el){
el.focus();
}
},
"color": {
bind: function(el,binding){
el.style.backgroundColor = binding.value.color;
}
}
}
实例:通过局部指令,分别添加光标定位和变化背景色的指令
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<input type="text" v-focus v-color="msg">
</div>
<script src="js/jquery-3.4.1.js"></script>
<script src="js/vue.js"></script>
<script>
var vm = new Vue({
el: "#app",
data: {
msg:{
color: "blue"
}
},
methods:{
},
directives:{
"focus": {
inserted: function(el){
el.focus();
}
},
"color": {
bind: function(el,binding){
el.style.backgroundColor = binding.value.color;
}
}
}
});
</script>
</body>
</html>
计算属性
- 概述
通过计算属性可以使模板中的表达式更加简洁,将模板中的计算逻辑进行抽取。
- 计算属性的用法
computed: {
reverseString: function(){
return this.msg.split("").reverse().join("");
}
}
实例:使用计算属性,实现将字符串进行反转的操作。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<div v-text="msg"></div>
<div v-text="reverseString"></div>
</div>
<script src="js/jquery-3.4.1.js"></script>
<script src="js/vue.js"></script>
<script>
var vm = new Vue({
el: "#app",
data: {
msg:"Hello World"
},
computed: {
reverseString: function(){
return this.msg.split("").reverse().join("");
}
}
});
</script>
</body>
</html>
- 计算属性与方法的区别
-
计算属性有缓存,当依赖的数据不发生改变时计算属性仅会被执行一次。
-
方法没有缓存,每次调用均会执行一次。
实例:通过多次调用,查看计算属性和方法分别被调用的次数。注意调用方法时需要加括号。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<div v-text="msg"></div>
<div v-text="reverseByComputed"></div>
<div v-text="reverseByComputed"></div>
<div v-text="reverseByMethods()"></div>
<div v-text="reverseByMethods()"></div>
</div>
<script src="js/jquery-3.4.1.js"></script>
<script src="js/vue.js"></script>
<script>
var vm = new Vue({
el: "#app",
data: {
msg:"Hello World"
},
methods:{
reverseByMethods: function(){
console.log("methods");
return this.msg.split("").reverse().join("");
}
},
computed: {
reverseByComputed: function(){
console.log("computed");
return this.msg.split("").reverse().join("");
}
}
});
</script>
</body>
</html>
监听器
- 应用场景
当数据变化时执行异步或者开销较大的操作。
- 监听器用法
watch: {
firstName: function(val){
this.fullName = val + " " + this.lastName;
},
lastName: function(val){
this.fullName = this.firstName + " " + val;
}
}
实例:通过监听器,监听姓和名的变化,从而动态改变全名的内容。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<div>
<span>名:</span>
<span>
<input type="text" v-model='firstName'>
</span>
</div>
<div>
<span>姓:</span>
<span>
<input type="text" v-model='lastName'>
</span>
</div>
<div>{{fullName}}</div>
</div>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript">
/*
侦听器
*/
var vm = new Vue({
el: '#app',
data: {
firstName: "Yorick",
lastName: "Jun",
fullName: "Yorick Jun"
},
watch: {
firstName: function(val){
this.fullName = val + " " + this.lastName;
},
lastName: function(val){
this.fullName = this.firstName + " " + val;
}
}
});
</script>
</body>
</html>
- 监听器案例,用于监听输入的改变,进行异步验证
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<input type="text" v-model.lazy="uname">
<span v-text="msg"></span>
</div>
<script src="js/jquery-3.4.1.js"></script>
<script src="js/vue.js"></script>
<script>
var vm = new Vue({
el: "#app",
data: {
uname: "",
msg: ""
},
methods: {
checkName: function(uname){
var that = this;
setTimeout(function(){
if(uname == "yorick"){
that.msg = "用户名已被注册,不可使用";
}else{
that.msg = "用户名可用";
}
},2000);
}
},
watch: {
uname: function(val){
this.checkName(val);
this.msg = "正在验证...";
}
}
});
</script>
</body>
</html>
过滤器
- 应用
用于对数据进行格式化操作。
- 全局自定义过滤器定义语法
Vue.filter("lower",function(val){
return val.charAt(0).toLowerCase() + val.slice(1);
});
- 局部自定义过滤器的定义语法
filters: {
upper: function(val){
return val.charAt(0).toUpperCase() + val.slice(1);
}
}
- 过滤器的使用
1.可以在插值表达式中使用
<div>{{msg | upper}}</div>
2.可以级联使用
<div>{{msg | upper | lower}}</div>
3.可以在属性绑定中使用
<div v-bind:id="id | formatId"></div>
实例:通过过滤器使得数据变为大写和小写开头。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<input type="text" v-model="msg">
<div>{{msg | upper}}</div>
<div>{{msg | upper | lower}}</div>
</div>
<script src="js/jquery-3.4.1.js"></script>
<script src="js/vue.js"></script>
<script>
// Vue.filter("upper",function(val){
// return val.charAt(0).toUpperCase() + val.slice(1);
// });
Vue.filter("lower",function(val){
return val.charAt(0).toLowerCase() + val.slice(1);
});
var vm = new Vue({
el: "#app",
data: {
msg: ""
},
filters: {
upper: function(val){
return val.charAt(0).toUpperCase() + val.slice(1);
}
}
});
</script>
</body>
</html>
- 带参数的过滤器
实例:通过带参数的过滤器实现对日期的格式化输出。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<div>{{date | format("yyyy-MM-dd")}}</div>
</div>
<script src="js/jquery-3.4.1.js"></script>
<script src="js/vue.js"></script>
<script>
Vue.filter("format",function(val,arg){
if(arg == "yyyy-MM-dd"){
var ret = "";
ret += val.getFullYear() + "-" + (val.getMonth() + 1) + "-" + val.getDate();
return ret;
}
return val;
});
var vm = new Vue({
el: "#app",
data: {
date: new Date()
},
});
</script>
</body>
</html>
生命周期
Vue实例的产生需要经过几个生命周期的函数调用。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<div>{{msg}}</div>
<button @click='update'>更新</button>
<button @click='destroy'>销毁</button>
</div>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript">
/*
Vue实例的生命周期
*/
var vm = new Vue({
el: '#app',
data: {
msg: '生命周期'
},
methods: {
update: function(){
this.msg = 'hello';
},
destroy: function(){
this.$destroy();
}
},
beforeCreate: function(){
console.log('beforeCreate');
},
created: function(){
console.log('created');
},
beforeMount: function(){
console.log('beforeMount');
},
mounted: function(){
console.log('mounted');
},
beforeUpdate: function(){
console.log('beforeUpdate');
},
updated: function(){
console.log('updated');
},
beforeDestroy: function(){
console.log('beforeDestroy');
},
destroyed: function(){
console.log('destroyed');
}
});
</script>
</body>
</html>
补充
- 数组的相关方法,Vue将原生的方法改变为了响应式
- 变异方法(修改原数据)
push()
pop()
shift()
unshift()
splice()
sort()
reverse()
- 替换数组(生成新的数组)
filter()
concat()
slice()
实例:通过push(),pop()动态增删列表元素,通过slice()截取元素。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<div>
<span>
<input type="text" v-model='fname'>
<button @click='add'>添加</button>
<button @click='del'>删除</button>
<button @click='change'>替换</button>
</span>
</div>
<ul>
<li :key='index' v-for='(item,index) in list'>{{item}}</li>
</ul>
</div>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript">
/*
Vue数组操作
1、变异方法:会影响数组的原始数据的变化。
2、替换数组:不会影响原始的数组数据,而是形成一个新的数组。
*/
var vm = new Vue({
el: '#app',
data: {
fname: '',
list: ['apple','orange','banana']
},
methods: {
add: function(){
this.list.push(this.fname);
},
del: function(){
this.list.pop();
},
change: function(){
this.list = this.list.slice(0,2);
}
}
});
</script>
</body>
</html>
- 修改响应式数据
通过以下API方法可以响应式的修改数组或者对象的数据。
Vue.set(vm.list,"1","lemon");
vm.$set(vm.list,"1","lemon");
实例:通过相关API修改数组和对象的属性值
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<ul>
<li :key='index' v-for='(item,index) in list'>{{item}}</li>
</ul>
<div>{{info.name}}</div>
<div>{{info.age}}</div>
</div>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript">
var vm = new Vue({
el: '#app',
data: {
list: ['apple','orange','banana'],
info: {
name: "alice",
age: 18
}
}
});
//修改数组的值
//Vue.set(vm.list,"1","lemon");
vm.$set(vm.list,"2","lemon");
//修改对象的值
// Vue.set(vm.info,"name","bob");
vm.$set(vm.info,"age",22);
</script>
</body>
</html>
案例
实现图书管理系统
1.图书的添加,修改,删除功能
2.过滤器格式化时间
3.监听器校验重名
4.自定义指令实现光标定位
5.计算属性实现图书数量的计算
6.生命周期函数实现通过后台服务器获取数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
.grid {
margin: auto;
width: 530px;
text-align: center;
}
.grid table {
border-top: 1px solid #C2D89A;
width: 100%;
border-collapse: collapse;
}
.grid th,td {
padding: 10;
border: 1px dashed #F3DCAB;
height: 35px;
line-height: 35px;
}
.grid th {
background-color: #F3DCAB;
}
.grid .book {
padding-bottom: 10px;
padding-top: 5px;
background-color: #F3DCAB;
}
.grid .total {
height: 30px;
line-height: 30px;
background-color: #F3DCAB;
border-top: 1px solid #C2D89A;
}
</style>
</head>
<body>
<div id="app">
<div class="grid">
<div>
<h1>图书管理</h1>
<div class="book">
<div>
<label for="id">
编号:
</label>
<input type="text" id="id" v-model='id' :disabled="idFlag" v-focus>
<label for="name">
名称:
</label>
<input type="text" id="name" v-model='name'>
<button @click='handle' :disabled="submitFlag">提交</button>
</div>
</div>
</div>
<div class="total">
<span>图书总数:</span>
<span>{{total}}</span>
</div>
<table>
<thead>
<tr>
<th>编号</th>
<th>名称</th>
<th>时间</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr :key="item.id" v-for="item in books">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>{{item.date | format("yyyy-MM-dd hh:mm:ss")}}</td>
<td>
<a href="" @click.prevent="editBook(item.id)">修改</a>
<span>|</span>
<a href="" @click.prevent="deleteBook(item.id)">删除</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript">
/*
图书管理-图书列表展示功能
*/
//自定义指令,实现光标定位
Vue.directive("focus",{
inserted: function(el){
el.focus();
}
});
//过滤器,实现时间的格式化输出
Vue.filter('format', function(value, arg) {
function dateFormat(date, format) {
if (typeof date === "string") {
var mts = date.match(/(\/Date\((\d+)\)\/)/);
if (mts && mts.length >= 3) {
date = parseInt(mts[2]);
}
}
date = new Date(date);
if (!date || date.toUTCString() == "Invalid Date") {
return "";
}
var map = {
"M": date.getMonth() + 1, //月份
"d": date.getDate(), //日
"h": date.getHours(), //小时
"m": date.getMinutes(), //分
"s": date.getSeconds(), //秒
"q": Math.floor((date.getMonth() + 3) / 3), //季度
"S": date.getMilliseconds() //毫秒
};
format = format.replace(/([yMdhmsqS])+/g, function(all, t) {
var v = map[t];
if (v !== undefined) {
if (all.length > 1) {
v = '0' + v;
v = v.substr(v.length - 2);
}
return v;
} else if (t === 'y') {
return (date.getFullYear() + '').substr(4 - all.length);
}
return all;
});
return format;
}
return dateFormat(value, arg);
});
var vm = new Vue({
el: '#app',
data: {
//控制提交按钮是否可用
submitFlag: false,
//控制编号输入框是否可用
idFlag: false,
id: "",
name: "",
books: []
},
methods: {
handle: function(){
//通过编号输入框是否可用来判别是修改还是添加
if(this.idFlag){
//修改
//使输入框可用
this.idFlag = false;
//遍历数组,将对应id的名字做修改
this.books.some((item)=>{
if(item.id == this.id){
item.name = this.name;
//跳出循环
return true;
}
});
}else{
//添加
var book = {};
book.id = this.id;
book.name = this.name;
book.date = new Date();
this.books.push(book);
}
//清空输入的数据
this.id = "";
this.name = "";
},
editBook: function(id){
//查找对应id的对象数组
var book = this.books.filter(function(item){
return item.id == id;
});
//数据回显到输入框,从数组中取数据,故需要索引
this.id = book[0].id;
this.name = book[0].name;
//设置编号输入框不可用
this.idFlag = true;
},
deleteBook: function(id){
//将除选中的删除数据外的其他数据重新赋值,实现删除
this.books = this.books.filter(function(item){
return item.id != id;
});
}
},
//计算属性
computed: {
total: function(){
return this.books.length;
}
},
//监听器
watch: {
name: function(val){
//监听到更改的名字与当前数组中的数据有重名,则提交按钮的状态做出对应改变
var flag = this.books.some(function(item){
return item.name == val;
});
this.submitFlag = flag;
}
},
//通过勾子函数从后台服务器获取数据
mounted: function(){
var data = [{
id: 1,
name: '三国演义',
date: new Date()
},{
id: 2,
name: '水浒传',
date: new Date()
},{
id: 3,
name: '红楼梦',
date: new Date()
},{
id: 4,
name: '西游记',
date: new Date()
}];
this.books = data;
}
});
</script>
</body>
</html>
网友评论