VUE的使用
一、简介
VUE是一个前端框架。是一个典型的MVVM模式的框架
MVVM
:模型、视图、视图模型。通过修改视图模型对象,就可以达到修改视图的目的,同样的,如果用户操作了视图,视图模型中也就自动的修改了操作结果注意:此框架中Ajax操作部分相对功能较复杂,一般会使用独立的第三方Ajax框架,例如axios。
**经典面试题:**vue的生命周期?
二、使用方式
有两种方案:
一、将VUE当做js使用,只需要在页面上引入js即可,比较简单
二、使用脚手架,需要下载node.js等工具或框架的支持,比较复杂,功能更强大
三、基础案例
- 导入vue.js
- 在页面上定义vue的使用区间和变量。(通过vue中使用el对应id)一般来说,页面上所有的需要vue来修改的变量必须全都包含在该id对应的元素中。下面的案例中的id即为app的一个div。
- 在js代码中使用vue的格式来定义Vue对象,并设置相应参数和变量的值。
data
用来定义属性,实例中两个属性分部为:msg
,url
。
methods
用于定义的函数,可以通过return
来返回函数值。
{{}}
用于输出对象属性和函数返回值。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="app">
<!--在里面为vue的有效区域-->
<h1>{{ msg }}</h1>
<h1>{{ url }}</h1>
<h1>{{ fn1() }}</h1>
</div>
</body>
</html>
<script>
var v = new Vue({
el:"#app", //指定vue框架有效区域对应的id
data:{ //data用于定义属性,在有效区域可以使用这些属性,但是需要加{{属性}}
msg:"hello,world",
url:"www.baidu.com"
},
methods:{ //methods 用于定义的函数
fn1:function() {
return this.msg + "你好世界";
}
}
})
</script>
四、基本语法
v-html
:输出html内容。例如:<div v-html="html1"</div>
v-bind
:属性名称:动态修改属性的值。例如:v-bind:href
。可以简写为::href
**注意:**html标签中的属性,需要动态修改时,一般在前面加上
v-bind:
如果是vue自定义的标签才会直接写,例如v-if
、v-show
、v-for
v-if:根据里面的变量的值,确定是否显示该标签
v-else-if:v-else,条件结构
v-show:根据里面的变量的值,确定是否显示该标签
template:本身没有任何作用,仅作为一个标签来包含其他标签进行集中控制
指令 | 作用 |
---|---|
v-bind | 为HTML标签绑定属性值,如设置 href , css样式等 |
v-model | 在表单元素上创建双向数据绑定 |
v-on | 为HTML标签绑定事件 |
v-if | 条件性的渲染某元素,判定为true时渲染,否则不渲染 |
v-else-if | |
v-else | |
v-show | 根据条件展示某元素,区别在于切换的是display属性的值 |
v-for | 列表渲染,遍历容器的元素或者对象的属性 |
4.1 插值
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
</head>
<style>
.class1{
background-color: red;
}
</style>
<body>
<div id="app">
<h1>{{msg}}</h1>
<!--输出html内容-->
<h1 v-html="msg"></h1>
<div>
<input type="checkbox" v-model="flag"/>
<div v-bind:class="{'class1':flag}">我是一个div</div>
</div>
<!--v-if可用于判断是否满足条件显示-->
<span v-if="flag">你看到我咯!!!</span><br>
<!--v-bind主要用于动态显示属性,可以缩写为 :属性-->
<a :href=url>百度一下</a>
<!--v-on:事件可以监听dom事件-->
<button v-on:click="fn1()">按钮</button><br>
<input type="text" v-model="textValue">绑定的数据:{{textValue}}<br>
<!--使用v-on来反转字符串,可以缩写为@-->
反转字符串:{{str}} <button @click="reverseStr()">点击反转</button><br>
<!--使用过滤器-->
首字母大写:{{str1 | filter1}}<br>
<!--template配合if可批量显示和隐藏-->
<template v-if="isShow">
<p>我是第一行</p>
<p>我是第二行</p>
<p>我是第三行</p>
</template>
<button @click="show()" >{{showStr}}</button><br>
<!--v-model控制复选框选择-->
爱好:<input type="checkbox" v-model="hobbys" value="1"/>跑步
<input type="checkbox" v-model="hobbys" value="2"/>睡觉
<input type="checkbox" v-model="hobbys" value="3"/>打游戏{{hobbys}}<br>
<!--显示隐藏图片-->
<img src="img/插值html.png" width="300px" v-show="img"/><br>
<button @click="imgShow()">{{imgText}}</button>
</div>
</body>
</html>
<script>
var v = new Vue({
el:'#app',
data:{
msg:"<a href='www.baidu.com'>www.baidu.com</a>",
flag:false,
url:"http://www.baidu.com",
textValue:"",
str:"Hello world",
str1:"hello",
isShow:true,
showStr:"点击我消失上面三行",
hobbys:[1,2],
img:true,
imgText:"隐藏图片"
},
//定义方法
methods:{
fn1:function(){
alert("被点击了一下")
},
reverseStr:function(){
return this.str = this.str.split('').reverse().join('')
},
show:function(){
this.isShow = !this.isShow
this.showStr = this.isShow?"点击我消失上面三行":"点击我显示隐藏内容"
},
imgShow:function(){
this.img = !this.img
this.imgText = this.img?"隐藏图片":"显示图片"
}
},
//定义过滤器
filters:{
filter1:function(value){
if(!value)return '';
value = value.toString();
//将首字母转为大写
return value.charAt(0).toUpperCase() + value.slice(1);
}
}
})
</script>
4.2 for
value在前,key在中间,index在最后
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<script src="js/vue.js"></script>
<body>
<div id="app">
<ul>
<template v-for="s in list">
<li>{{s}}</li>
<li>----</li>
</template>
</ul>
<!--如果迭代对象,value在前,key在中间,index在最后-->
<ul>
<!--第一个始终时value,如果需要key,那么就需要两个变量接收-->
<template v-for="s in object">
<li>{{s}}</li>
<li>----</li>
</template>
</ul>
<ul>
<template v-for="(value,key) in object">
<li>{{key}}:{{value}}</li>
<li>---</li>
</template>
</ul>
<ul>
<template v-for="(value,key,index) in object">
<li>索引{{index}}:键{{key}}:值{{value}}</li>
<li>----</li>
</template>
</ul>
<ul>
遍历结果为:
<template v-for="i in 15">
{{i}},
</template>
</ul>
</div>
</body>
</html>
<script>
var v = new Vue({
el:"#app",
data: {
list: ['one','two','three','four'],
object:{name:'张三',age:'50',gender:'1'}
},
methods:{
}
})
</script>
4.3 监听
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<script src="js/vue.js"></script>
<body>
<div id="app">
<h1>计数器:{{count}}</h1><br />
<button @click="count++">点击</button>
<div>
千米:<input type="text" v-model="km"/>
米:<input type="text"v-model="m"/>
</div>
<p id = "info"></p>
</div>
</body>
</html>
<script>
var v = new Vue({
el:"#app",
data:{
count:1,
m:0,
km:0
},
watch:{
km:function(val){
this.km = val
this.m = this.km * 1000
},
m:function(val){
this.m = val
this.km = this.m / 1000
}
}
})
v.$watch('count', function(nval, oval) {
alert('计数器值的变化 :' + oval + ' 变为 ' + nval + '!');
})
v.$watch('km',function(newVal,oldVal){
document.getElementById("info").innerHTML = "修改前值为" + oldVal + ",修改后值为" + newVal
})
</script>
4.4 表单
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<script src="js/vue.js"></script>
<body>
<div id="app">
<h1>input元素:{{message1}}</h1>
<input type="text" v-model="message1" placeholder="编辑我" /><br>
<!--style="white-space: pre;"该样式控制了文字换行-->
<p style="white-space: pre;">textarea元素:{{message2}}</p>
<textarea v-model="message2" placeholder="多行文本输入"></textarea>
<h1>单个单选框</h1>
<input type="checkbox" id="check1" v-model="checked1"/><label for="check1">{{checked1}}</label><br>
<h1>复选框:</h1>
<input type="checkbox" id="red" value="red" v-model="checked2"/><label for="red">red</label>
<input type="checkbox" id="green" value="green" v-model="checked2"/><label for="green">green</label>
<input type="checkbox" id="yellow" value="yellow" v-model="checked2"/><label for="yellow">yellow</label>
<p>选择的值:{{checked2}}</p>
<h1>单选按钮:</h1>
<input type="radio" id="man" value="男" v-model="radio1"/><label for="man">男</label>
<input type="radio" id="girl" value="女" v-model="radio1"/><label for="girl">女</label><br>
选中了:{{radio1}}
<h1>复选框</h1>
<select v-model="selected">
<option value="">选择一个省份</option>
<option value="0">湖北</option>
<option value="1">湖南</option>
<option value="2">广东</option>
</select>
选中了省份是第几个:{{selected}}
</div>
</body>
</html>
<script>
var v = new Vue({
el:"#app",
data:{
message1:"我是",
message2:"我是\n你是",
checked1:true,
checked2:['red','green'],
radio1:'女', //默认选中女
selected:'1', //默认选中第一个选项
}
})
</script>
五、axios的基本用法
axios是一个ajax框架,简化了各种ajax操作,有强大的ajax操作功能
5.1 get请求
语法:
axios.get(“url”,[params]) //url和参数
.then(function(res){}) //回调
.catch(function(ex){}); //异常捕获
//因为我后台采用result风格接收请求,所以这里拼接id,如果后台使用普通GetMapping接收请求,可以写成
// axios.get('http://localhost:8080/student/preupdate',{
// params:{
// id:1
// }
// })
// .then(function(resp){
// console.log(resp)
// })
// .catch(function(error) {
// console.log(error)
// })
//为指定 ID 的 student 创建请求
axios.get('http://localhost:8080/student/preupdate/' + 10)
.then(function(resp){
if(resp.data.code == "10000"){
console.log(resp.data.data)
}else{
console.log(resp.data.desc)
}
})
.catch(function(error) {
console.log(error)
})
//此处then方法也可以将上面的匿名函数写成箭头函数
axios.get('http://localhost:8080/student/preupdate/' + 10)
.then((resp)=>{
if(resp.data.code == "10000"){
console.log(resp.data.data)
}else{
console.log(resp.data.desc)
}
})
.catch((error) => {
console.log(error)
})
5.2 post请求
语法:
axios.post(“url”,paramobj) //url和参数
.then(function(res){}) //回调
.catch(function(ex){}) //异常捕获
注意:此处请求与jQuery完全不同
jQuery如果按照此处直接传json对象的参数的话,后台应该使用request.getParameter方式接收,也就是说默认为表单提交类型,即application/x.www.form-urlencoded,如果是对象,后台springmvc中直接使用对象接收即可。
axios如果直接传json对象,默认是json格式传参,即application/json,也就是以流的形式提交,后台必须使用
@RequestBody
方式接收参数
//@RequestBody接收
axios.post("http://127.0.0.1:8080/student/save",{
name:"zhangsan",
sex:'男'
}).then(function(resp){
if(resp.data.code == "10000"){
alert(JSON.stringify(resp.data.data))
}else{
alert(resp.data.desc)
}
})
//普通post接收(两种方式)
//1. 拼接
axios.post("http://127.0.0.1:8080/student/update?id=34&name=lisi&sex=女").then(function(resp){
if(resp.data.code == "10000"){
alert(JSON.stringify(resp.data.data))
}else{
alert(resp.data.desc)
}
})
//2. params传参方式,需要使用第三个参数才能用params方式
axios.post("http://127.0.0.1:8080/student/update",null,{
params:{
id:34,
name:'zhangsan',
age:20
}
}).then(function(resp){
if(resp.data.code == "10000"){
alert(JSON.stringify(resp.data.data))
}else{
alert(resp.data.desc)
}
})
5.3 并发请求
//执行多个并发请求
function getGrade(){
return axios.get("http://127.0.0.1:8080/student/grades");
}
function deleteById(){
return axios.get("http://127.0.0.1:8080/student/delete",{
params:{
id:34
}
})
}
axios.all([getGrade(),deleteById()])
.then(axios.spread(function (grades,dele){
//两个请求现在都执行并返回结果
console.log(grades)
console.log(dele)
}))