1. export
的使用
编写 request.js
文件
const get = (urlShard) => {
let request = new XMLHttpRequest();
request.onreadystate = () => {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
return JSON.parse(request.response);
}
}
};
request.open("GET", "https://www.example.com/" + urlShard, false);
request.setRequestHeader("Content-Type", "application/json");
request.send()
};
const post = (urlShard, data) => {
let request = new XMLHttpRequest();
request.onreadystate = () => {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
return JSON.parse(request.response);
}
}
};
request.open("POST", "https://www.example.com/" + urlShard, false);
request.setRequestHeader("Content-Type", "application/json");
request.send(data)
};
// export get;
export {
get,
post
};
编写 index.js
文件
// import { get } from "/path/to/request.js";
import { get, post } "/path/to/request.js";
const getItem = (itemId) => {
const urlShard = "item" + itemId ? "/" + itemId : "";
return get(urlShard);
};
const addItem = (item) => {
const urlShard = "item";
return post(urlShard, item);
};
2. export default
的使用
编写 request.js
文件
const request = {
get: (urlShard) => {
let request = new XMLHttpRequest();
request.onreadystate = () => {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
return JSON.parse(request.response);
}
}
};
request.open("GET", "https://www.example.com/" + urlShard, false);
request.setRequestHeader("Content-Type", "application/json");
request.send()
};
post: (urlShard, datal) => {
let request = new XMLHttpRequest();
request.onreadystate = () => {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status === 200) {
return JSON.parse(request.response);
}
}
};
request.open("POST", "https://www.example.com/" + urlShard, false);
request.setRequestHeader("Content-Type", "application/json");
request.send(data)
};
}
export default Request;
编写 index.js
文件
import req from "/path/to/request.js";
const getItem = (itemId) => {
const urlShard = "item" + itemId ? "/" + itemId : "";
return new req.get(urlShard);
};
const addItem = (item) => {
const urlShard = "item";
return new req.post(urlShard, item);
};
3. 总结
export
是对外开放此模块内,多个常量
、变量
、函数
或类
作为接口,引用时需要知道名称,且要包含在花括号({})
内,多个要用逗号(,)
分隔;
export default
是对外开放此模块内,某一个常量
、变量
、函数
或类
作为此模块的默认接口,一个文件有且只有一个 export default
,引用时不需要知道名称,可自定义名称。
export default
和 export
可以一起使用。
网友评论