目錄
一.mock資料
二.$nextTick()
三.資料互動
一.mock資料
1.定義
mock serve工具,通俗來說,就是模擬服務端介面資料,一般用在前后端分離后,前端人員可以依賴API開發,在本地搭建一個JSON服務,自己產生測驗資料,即json-server就是個存盤json資料的serve,
注:json-server支持CORS和JSONP跨域請求,
2.json-server
使用步驟:
- 初始化專案:npm init -y
- 安裝json-server npm i json-server -D
- 打開專案撰寫資料
在專案根目錄下創建db.json,并寫上合法的json資料,
- 啟動配置
在package.json下增加如下代碼:
"scripts": {
"server":"json-server db.json"
}
- 運行
在命令列運行:npm run server
二.$nextTick()
1.應用場景:資料更新影響的(新的)dom時,使用$nextTick(),
三.資料互動
1.向服務器發送ajax請求,獲取資料,
2.解決方案
- 通過XMLHttpReauest物件封裝一個ajax;

function ajax(options) {
//1.創建物件
var xhr = new XMLHttpRequest();
//2.處理引數——get請求的引數在open中,即拼接在url后面,post請求的引數在send中
var params = formsParams(options.data);
// 3.判斷請求方式
if (options.type == "GET") {
xhr.open(options.type, options.url + "?" + params, options.async);
xhr.send(null)
}
if (options.type == "POST") {
xhr.open(options.type, options.url, options.async);
//請求頭
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(params);
}
//4.設定回呼函式
xhr.onreadystatechange = function () {
//xhr.readyState == 4請求成功xhr.status == 200回應完成
if (xhr.readyState == 4 && xhr.status == 200) {
options.success(xhr.responseText);
}
}
function formsParams(data) {
var arr = [];
for (var key in data) {
//用=將字串分隔,再將值插入到arr陣列中
//key是物件的鍵,data[key]是鍵對應的值
arr.push(key+ "=" + data[key]);
}
return arr.join("&");
}
}
ajax({
url: "地址", // url---->地址
type: "POST", // type ---> 請求方式
async: true, // async----> 同步:false,異步:true
data: { //傳入資訊
name: "張三",
age: 18
},
success: function (data) { //回傳接受資訊
console.log(data);
}
})
- 使用第三方自帶的ajax庫,(jquery)
使用步驟:
1.在.vue檔案中,script標簽外面引入jquery,
import $ from “jquery”;
2.直接發送請求,即可,注意發送請求的時機,
- ES6新增的fetch
格式:fetch(String url,配置),回傳的是一個Promise物件,
fetch(url,{
method:
headers:
body:
//body:請求body資訊,可能是一個 Blob、BufferSource、FormData、URLSearchParams 或者 USVString 物件,注意 GET 或 HEAD 方法的請求不能包含 body 資訊,
})
//get方式
fetch(url?id=001,
{method:'GET'
})
.then(response => response.json()) //response.json()將后端回傳的資料,轉換為json格式
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e))
//post方式
fetch(url,{
method:"POST",
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式為表單提交
}),
body: "id=001&name=張三瘋" // post請求的引數
})
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.log("Oops, error", e))
特點:
1.fetch請求默認不帶cookie,需要設定fetch(url,{credentials:'include'});
2.服務器回傳400,500錯誤碼時并不會reject,只有網路錯誤導致請求不能完成時,fetch才會被reject,
- 使用第三方ajax封裝成promise習慣的庫,
1.定義:
一個基于promise的第三方庫,可以用在瀏覽器(前端)和nodej.js(后端)中,
2.格式
axios({
url : “地址“
method: “ 提交方式”
params:{} 地址欄攜帶的資料(get方式)
data:{} 非地址欄攜帶資料(如:post,put等等),
baseURL:如果url不是絕對地址,那么將會加在其前面,當axios使用相對地址時這個設定非常方便
}).then(res=>{
console.log(res.data);
})
axios的完整格式和axios的別名(get和post)
axios({配置}).then(成功回呼(res)).catch(失敗回呼(res))
axios.get(url,{配置}).then(成功回呼(res)).catch(失敗回呼(res))
axios.post(url,{配置}).then(成功回呼(res)).catch(失敗回呼(res))
注:回應體,資料是在res.data內部,
eg:get請求
axios({
url:'getGoodsListNew.php',
// method:'get', 默認是get請求
params:{
count:3
}
})
.then(res=>this.goodslist=res.data);
eg:post請求
1)data是字串
當data是字串時,請求頭里的content-type是application/x-www-form-urlencoded,network中看到的資料型別是:formData,
axios(
{
method:'post',
url:'regSave.php',
data:'username=jzmdd&userpass=123'
})
.then(res=>{ …………………… });
2)data是URLSearchParams物件
當data是URLSearchParams物件時,同data是字串,
var params = new URLSearchParams();
params.append('username', 張三瘋);
params.append('userpass', '123');
axios(
{
method:'post',
url:'regSave.php',
data:params
})
.then(res=>{ …………………… });
3)data是json物件
當data是json物件時,請求頭里的content-type是application/json,network中看到的資料型別是:request payload,
axios({
url:"/vips",
method:"post",
data:{
name:this.name,
pass:this.pass,
sex:this.sex
},
baseURL:"http://localhost:3000"
})
.then(res=>console.log(res.data))
3.[面試]Ajax,jQuery ajax,axios和fetch的區別
- ajax是最早出現的前后端互動技術,是原生js,核心使用的是XMLHttpRequest物件,多個請求之間如果有先后關系,就會出現回呼地獄,(利用promise解決哦)
- fetch是ES6新增的,fetch是基于promise設計的,fetch不是ajax的進一步封裝,而是原生js,fetch函式就是原生js,沒有使用XMLHttpRequest物件,
- jQuery ajax是原生ajax的封裝;
- axios是原生ajax的封裝,基于promise物件,axios也可以在請求和回應階段進行攔截,它不但可以在客戶端使用,也可以在node.js端使用,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/293370.html
標籤:其他
下一篇:Java專案:校園跑腿管理系統(java+Springboot+vue+maven+elementui+mysql)
