// 定義工具方法
let Util = {
? ? /**
? ? * 發(fā)送異步請(qǐng)求
? ? * @url 請(qǐng)求的地址
? ? * @fn 請(qǐng)求成功時(shí)候的回調(diào)函數(shù)
? ? **/
? ? getData(url, fn) {
? ? ? ? // 實(shí)例化xhr對(duì)象
? ? ? ? let xhr = new XMLHttpRequest();
? ? ? ? // 監(jiān)聽(tīng)狀態(tài)變化
? ? ? ? xhr.onreadystatechange = () => {
? ? ? ? ? ? // 監(jiān)聽(tīng)數(shù)據(jù)請(qǐng)求完畢
? ? ? ? ? ? if (xhr.readyState === 4) {
? ? ? ? ? ? ? ? // 判斷狀態(tài)碼
? ? ? ? ? ? ? ? if (xhr.status === 200) {
? ? ? ? ? ? ? ? ? ? // 將數(shù)據(jù)轉(zhuǎn)化成json字符串
? ? ? ? ? ? ? ? ? ? fn && fn(JSON.parse(xhr.responseText))
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? // 打開(kāi)請(qǐng)求
? ? ? ? xhr.open('GET', url, true);
? ? ? ? // 發(fā)送數(shù)據(jù)
? ? ? ? xhr.send(null)
? ? },
? ? postData(url, params, fn) {
? ? ? ? // 實(shí)例化xhr對(duì)象
? ? ? ? let xhr = new XMLHttpRequest();
? ? ? ? // 監(jiān)聽(tīng)狀態(tài)變化
? ? ? ? xhr.onreadystatechange = () => {
? ? ? ? ? ? // 監(jiān)聽(tīng)數(shù)據(jù)請(qǐng)求完畢
? ? ? ? ? ? if (xhr.readyState === 4) {
? ? ? ? ? ? ? ? // 判斷狀態(tài)碼
? ? ? ? ? ? ? ? if (xhr.status === 200) {
? ? ? ? ? ? ? ? ? ? // 將數(shù)據(jù)轉(zhuǎn)化成json字符串
? ? ? ? ? ? ? ? ? ? fn && fn(JSON.parse(xhr.responseText))
? ? ? ? ? ? ? ? }
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? // 打開(kāi)請(qǐng)求
? ? ? ? xhr.open('POST', url, true);
? ? ? ? xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded; charset=utf-8");
? ? ? ? // 發(fā)送數(shù)據(jù)
? ? ? ? xhr.send(params);
? ? },
? ? /**
? ? * 將對(duì)象轉(zhuǎn)化成query的形式
? ? * @obj 轉(zhuǎn)化的對(duì)象 {color:red, num:100}
? ? * return ?color=red&num=100
? ? **/
? ? objToQuery(obj,type) {
? ? ? ? type = type ? '':'?';
? ? ? ? let result = '';
? ? ? ? // 遍歷對(duì)象,轉(zhuǎn)化成json
? ? ? ? for (var i in obj) {
? ? ? ? ? ? result += '&' + i + '=' + obj[i]
? ? ? ? }
? ? ? ? // 去除最后一個(gè)&
? ? ? ? return type + result.slice(1)
? ? }
}
new Vue({
? el:"#app",
? data:{
? ? msg:"hello world",
? ? list:[]
? },
? created:function(){
? ? var that = this;
? ? // 提供post,get請(qǐng)求
? ? Util.getData("https://a.daxiangclass.com/offer.php/api/v1/interview?page=1&size=100",function(res){
? ? ? ? that.list = res.data;? ? ?
? ? });
? }
})
{{item.title}}
在HTML文檔
<p>{{item.title}}</p>//渲染數(shù)據(jù)