JavaWEB笔记17 Vue发送AJAX+生命周期函数+案例

JavaWEB笔记17 Vue发送AJAX+生命周期函数+案例

一.Vue发送AJAX:

Vue中发送AJAX需要依托以下两种.js文件,分别是:axios.min.js(新版)以及vue-resource.min.js,这两个.js文件发送AJAX时有不同,以下将介绍:

  • 1)引入库:vue-resource来发送AJAX请求
  • 2)在Vue的methods中设计对应的请求方法:
this.$http.get('url').then(function(res){
	请求成功的函数
}),function(){
	请求失败的函数
}
  • 注意:
    get请求后面url不想在 ? 后拼参就使用params:{ 属性:值 },url中的包含 ? 以及后面所有均删掉,格式如下:get('url',params:{ 属性:值 })
  • 3)POST请求在上面get换成post,键值对前面的params不写,后面再加上{emulateJSON : true}返回JSON类型的数据,注意在AJAX请求中then中进行调用this,是Vue对象可以直接调用,可以在使用之前进行对应判断
  • 4)Vue-resource库在2.0以上被废掉了,但是该库好处在于可以发送jsonp请求:
this.$http.jsonp(url,
	{params:{键:值},
	jsonp:'cb或callback'   //cb是默认百度的callback
	})
.then(res=>{ 成功请求 })
  • 5)新版本库:Vue.anxios(不支持jsonp,只能用origin) 发送AJAX:其中get方法:
axios.get('url',{
	params:{键:值}
	}).then(response=>{请求成功}).catch(){ 
	//请求失败的相关处理 
	}

注意此处this与上面的不同,此处this指向的对象并不是Vue对象

二.Vue生命周期函数:

首先引入几个概念:

  • 生命周期: 一个事物从生到死所经历的不同阶段,在不同阶段可以做不同的事
  • Vue生命周期: Vue对象从创建到销毁的一个过程
  • Vue的生命周期也是Vue在不同阶段会调用不同的函数,我们就叫做Vue的生命周期函数

Vue生命周期函数的案例:

  • 需求: 文本隔一秒闪一次
  • 分析: 需求有两部分:
    v-show以及定时器结合生命周期函数
    mounted函数: 模板挂载完毕,数据也准备完成之后的周期函数,与methods存在的位置并列
  • 循环定时器:
mounted:function(){ 
	var tm = setInterval(()=>{
		this.flag=!this.flage
		},1000)}
  • 停止闪烁:
metods: { 
	stop(){ 
	this.$destroy(); 
	}} //销毁Vue对象实例
  • 善后工作: 停止计时器的计时:
beforeDestroy:function(){ 
	clearInterval(tm); 
	} //关闭定时器

(注意:同样与上面的mounted位置相同,与methods位置并列)


最常用的两个函数就是mounted挂载完毕beforeDestroy销毁前善后,el生命周期阶段较早,其他都不常用,关于生命周期函数的其他知识,详情见下图:
在这里插入图片描述
在这里插入图片描述

三.过滤器:

Vue中过滤器的作用是处理字符串并显示:

  • 将一个字符串进行首字母大写且其余字符小写:
msg.substring(0,1).toUpperCase().concat(msg.substr(1).toLowerCase())
  • 过滤器filters:{} 可以定义多个过滤器,与methods位置并列
    比如说上面就可以直接定义为
changeText(value) //其中value需要传参

在上面的标签文本处进行调用时:{{msg|changText}}就可以将msg作为value传值了

  • 过滤器的连续使用:
{{msg|changeText|change2|change3}} //是一种层层过滤的形式
  • 过滤器中传参:传多个参数,被过滤主体对象放第一个形参,后面放新形参,调用有:{{msg|format(a)}}
  • ES6中在定义过滤器中可以直接给形参一个过滤器,即:
change(value,a='YYYY-DD-MM')
  • 过滤器分为两种:局部过滤器全局过滤器
    1)局部过滤器:只能当前这个Vue实例所控制的模板中使用
    2)全局过滤器:在所有的Vue实例控制的区域中都生效,出现的地方在new之前,使用Vue.filter('过滤器名',function(){})直接进行定义

四.Vue中获取原生DOM对象:

Vue中基本上不常用,其效果同document.getElementById(),实例:更改标签对象中的内部文本:

  • 1)对应button绑定事件show($event):e.target.innerText=""
  • 2)原生DOM进行操作
  • 3)Vue中特有:ref="h" 在下面的函数中:this.$refs.h进行调用

五.案例一:Vue版天气预报:

需求:
给定一个CSS样式,完成使用Vue发送AJAX请求来查询中国城市的天气,并将其显示
代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>天知道</title>
    <link rel="stylesheet" href="css/reset.css" />
    <link rel="stylesheet" href="css/index.css" />
    <script type="text/javascript" src="axios.min.js" charset="UTF-8"></script>
    <script type="text/javascript" src="vue.js"></script>
</head>
<body>
<div class="wrap" id="app">
    <div class="search_form">
        <div class="logo"><img src="img/logo.png" alt="logo" /></div>
        <div class="form_group">
            <input type="text"  id="cityName" class="input_txt" placeholder="请输入查询的天气" v-model="cityName"  @keyup.enter="sendJSONP(cityName)"/>
            <button class="input_sub" @click="sendJSONP(cityName)">
                搜 索
            </button>
        </div>
        <div class="hotkey">
            <a href="javascript:;" @click="sendJSONP('北京')">北京</a>
            <a href="javascript:;" @click="sendJSONP('上海')">上海</a>
            <a href="javascript:;" @click="sendJSONP('广州')">广州</a>
            <a href="javascript:;" @click="sendJSONP('深圳')">深圳</a>
        </div>
    </div>
    <ul class="weather_list" v-show="flag">
        <li v-for="(item,index) in weatherList" :key="index">
           <div class="info_type"><span class="iconfont">{{item.weather}}</span></div>
           <div class="info_temp">
               <b>{{item.lowtemp}}</b>
                 ~
               <b>{{item.hightemp}}</b>
            </div>
            <div class="info_date"><span>日期: {{item.date}}</span></div>
         </li>
    </ul>
</div>
<script type="text/javascript">
    new Vue({
        el: '#app',
        data: {
            weatherList: [
                {weather: '', date: '', lowtemp: '', hightemp: ''},
                {weather: '', date: '', lowtemp: '', hightemp: ''},
                {weather: '', date: '', lowtemp: '', hightemp: ''},
                {weather: '', date: '', lowtemp: '', hightemp: ''},
                {weather: '', date: '', lowtemp: '', hightemp: ''}
            ],
            cityName: '',
            flag: false
        },
        methods:{
            sendJSONP(cityname){
                axios.get('http://wthrcdn.etouch.cn/weather_mini', {
                        params: { city : cityname }
                    }).then(res=>{
                        if(res.data.desc==="invilad-citykey"){
                            alert("请输入正确的城市!");
                            this.cityName = '';
                            this.flag = false;
                        }
                        else {
                            this.flag = true;
                            console.log(res);
                            var obj = res.data;
                            //将得到的数据放入weatherList
                            for (var i = 0; i < 5; i++) {
                                this.weatherList[i].weather = obj.data.forecast[i].type;
                                this.weatherList[i].date = obj.data.forecast[i].date;
                                this.weatherList[i].lowtemp = obj.data.forecast[i].low;
                                this.weatherList[i].hightemp = obj.data.forecast[i].high;
                            }
                        }
                })
            }
        }
    })
</script>
</body>
</html>

其中使用到的给定CSS:

//index.CSS如下:
body{
    font-family:'Microsoft YaHei';   
}
.wrap{
    position: fixed;
    left:0;
    top:0;
    width:100%;
    height:100%;
    /* background: radial-gradient(#f3fbfe, #e4f5fd, #8fd5f4); */
    /* background:#8fd5f4; */
    /* background: linear-gradient(#6bc6ee, #fff); */
    background:#fff;

}
.search_form{
    width:640px;
    margin:100px auto 0;
}
.logo img{
    display:block;
    margin:0 auto;
}
.form_group{
    width:640px;
    height:40px;
    margin-top:45px;
}
.input_txt{
   width:538px;
   height:38px;
   padding:0px;
   float:left;
   border:1px solid #41a1cb;
   outline:none;
   text-indent:10px;
}

.input_sub{
    width:100px;
    height:40px;
    border:0px;
    float: left;
    background-color: #41a1cb;
    color:#fff;
    font-size:16px;
    outline:none;
    cursor: pointer;
    position: relative;
}
.input_sub.loading::before{
    content:'';
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background: url('../img/loading.gif');
}

.hotkey{
    margin:3px 0 0 2px;
}

.hotkey a{
    font-size:14px;
    color:#666;
    padding-right:15px;
}
.weather_list{
    height:200px;
    text-align:center;
    margin-top:50px;
    font-size:0px;
}
.weather_list li{
    display:inline-block;
    width:140px;
    height:200px;
    padding:0 10px;
    overflow: hidden;
    position: relative;
    background:url('../img/line.png') right center no-repeat;
    background-size: 1px 130px;
}

.weather_list li:last-child{
    background:none;
}

/* .weather_list .col02{
    background-color: rgba(65, 165, 158, 0.8);
}
.weather_list .col03{
    background-color: rgba(94, 194, 237, 0.8);
}
.weather_list .col04{
    background-color: rgba(69, 137, 176, 0.8);
}
.weather_list .col05{
    background-color: rgba(118, 113, 223, 0.8);
} */


.info_date{
    width:100%;
    height:40px;
    line-height:40px;
    color:#999;
    font-size:14px;
    left:0px;    
    bottom:0px;    
    margin-top: 15px;
}
.info_date b{
    float: left;
    margin-left:15px;
}

.info_type span{
    color:#fda252;
    font-size:30px;
    line-height:80px;
}
.info_temp{
    font-size:14px;  
    color:#fda252;
}
.info_temp b{
    font-size:13px;
}
.tem .iconfont {
    font-size: 50px;
  }

效果:
初始界面:
在这里插入图片描述
点击界面上给定城市(北上广深)的效果:
在这里插入图片描述
搜索国内城市进行查询的效果:
在这里插入图片描述
所搜索的城市找不到或搜索不合法时的弹窗效果:
在这里插入图片描述

六.案例二:Vue版手机归属地查询:

需求:
使用CSS并结合Vue中发送AJAX完成设计一个手机归属地查询的网页
代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue版手机归属地查询</title>
    <script type="text/javascript" src="vue.js" charset="UTF-8"></script>
    <script type="text/javascript" src="vue-resource.min.js"></script>
    <style type="text/css">
        *{
            list-style: none;
        }
        #topElem{
            margin-top: 20px;
            width: 60%;
            margin-left: 20%;
        }
        #top{
            font-size: 40px;
            width: 100%;
            height: 50px;
            line-height: 50px;
            text-align: center;
            margin-left: -30px;
        }
        #haomaduan{
            font-size: 20px;
            margin-top: 25px;
            margin-left: 10px;
        }
        #srch{
            border: gray solid 1px;
            width: 75%;
            height: 36px;
            margin-top: 20px;
        }
        .btn{
            width: 100px;
            height: 41px;
            border: none;
            background-color: #3fac24;
            color: white;
            font-size: 20px;
            position: absolute;
            left: 65%;
            top: 141px;
        }
        .btn:hover{
            cursor: pointer;
        }
        #bodypart{
            position: relative;
            width: 66%;
            margin-left: 17%;
            margin-top: 30px;
        }
        #chaxjg{
            position: absolute;
            width: 92%;
            height: 45px;
            background-color: rgba(154, 150, 143, 0.56);
            border: gray solid 1px;
            text-align: center;
            line-height: 40px;
            font-size: 20px;
        }
        #number{
            position: absolute;
            top: 47px;
            border: lightgray solid 1px;
            width: 46%;
            height: 42px;
            text-align: center;
            line-height: 45px;
            font-size: 18px;
        }
        #number_json{
            position: absolute;
            top: 47px;
            left: 46%;
            border: lightgray solid 1px;
            width: 46%;
            height: 42px;
            text-align: center;
            line-height: 45px;
            font-size: 18px;
        }
        #cityinfo{
            position: absolute;
            top: 91px;
            border: lightgray solid 1px;
            width: 46%;
            height: 42px;
            text-align: center;
            line-height: 45px;
            font-size: 18px;
        }
        #cityinfo_json{
            position: absolute;
            top: 91px;
            left: 46%;
            border: lightgray solid 1px;
            width: 46%;
            height: 42px;
            text-align: center;
            line-height: 45px;
            font-size: 18px;
        }
        #companyinfo{
            position: absolute;
            top: 135px;
            border: lightgray solid 1px;
            width: 46%;
            height: 42px;
            text-align: center;
            line-height: 45px;
            font-size: 18px;
        }
        #companyinfo_json{
            position: absolute;
            top: 135px;
            left: 46%;
            border: lightgray solid 1px;
            width: 46%;
            height: 42px;
            text-align: center;
            line-height: 45px;
            font-size: 18px;
        }
        #cityblock{
            position: absolute;
            top: 179px;
            border: lightgray solid 1px;
            width: 46%;
            height: 42px;
            text-align: center;
            line-height: 45px;
            font-size: 18px;
        }
        #cityblock_json{
            position: absolute;
            top: 179px;
            left: 46%;
            border: lightgray solid 1px;
            width: 46%;
            height: 42px;
            text-align: center;
            line-height: 45px;
            font-size: 18px;
        }
        #postcode{
            position: absolute;
            top: 223px;
            border: lightgray solid 1px;
            width: 46%;
            height: 42px;
            text-align: center;
            line-height: 45px;
            font-size: 18px;
        }
        #postcode_json{
            position: absolute;
            top: 223px;
            left: 46%;
            border: lightgray solid 1px;
            width: 46%;
            height: 42px;
            text-align: center;
            line-height: 45px;
            font-size: 18px;
        }
        #moreinfo{
            position: absolute;
            top: 267px;
            border: lightgray solid 1px;
            width: 92%;
            height: 50px;
            text-align: center;
            line-height: 50px;
            font-size: 20px;
            color: #3fac24;
            text-decoration: none;
        }
        #moreinfo:hover{
            cursor: pointer;
        }
    </style>
</head>
<body>
<div id="box">
    <div id="topElem">
        <div id="top">手机号码归属地专业查询</div>
        <div id="haomaduan">手机号码():</div>
        <input value="" id="srch" type="text" placeholder="请输入需要查询的手机号码" v-model="mobile"  @keyup.enter="sendGETJSONP()"/>
        <button type="button" class="btn" @click="sendGETJSONP()">查询</button>
    </div>
    <div id="bodypart" v-if="flag">
        <div id="chaxjg">查询结果</div>
        <div id="number">您查询的手机号码段</div>
        <div id="number_json">{{mobilex}}</div>
        <div id="cityinfo">卡号归属地</div>
        <div id="cityinfo_json">{{cityinfo}}</div>
        <div id="companyinfo">隶属通讯公司</div>
        <div id="companyinfo_json">{{company}}</div>
        <div id="cityblock">区号</div>
        <div id="cityblock_json">{{cityblock}}</div>
        <div id="postcode">邮编</div>
        <div id="postcode_json">{{postcode}}</div>
        <a id="moreinfo" href="https://cn.bing.com/search?q=%E4%B8%AD%E5%9B%BD%E5%90%84%E5%9C%B0%E9%82%AE%E7%BC%96%E5%8C%BA%E5%8F%B7&cvid=a2ac39fe100d44c09adb0281ce434de5&aqs=edge..69i57j0.9831j0j1&pglt=41&FORM=ANNTA1&PC=DCTS">更多详情邮编区号</a>
    </div>
</div>
<script type="text/javascript">
    new Vue({
        el: '#box',
        data: {
            flag : false,
            mobile: '',
            cityinfo: '',
            company : '',
            cityblock: '',
            postcode: '',
            mobilex:''
        },
        methods:{
            sendGETJSONP(){
                this.flag = true;
                this.$http.jsonp('https://tool.bitefu.net/shouji/',{
                    params: { mobile : this.mobile },
                    emulateJSON : true,
                    jsonp: "callback"
            }).then(resdata=>{
                console.log(resdata);
                if(resdata.body.info){
                    alert(resdata.body.info);
                    this.mobilex = '';
                }
                else {
                    this.mobilex = resdata.body.mobile;
                    this.cityinfo = resdata.body.province + ' ' + resdata.body.city;
                    this.company = resdata.body.isp;
                    this.cityblock = resdata.body.areacode;
                    this.postcode = resdata.body.postcode;
                }
                    }
                )
            }
        }
    }
    )
</script>
</body>
</html>

效果:
JavaWEB笔记14 jQuery发送AJAX和JAVA后台JSON数据中案例的效果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值