1.前言
1.書(shū)接上文vue3 ts核心語(yǔ)法
2.這個(gè)主要是接口類型 和axios的用法
3.還有promise async wait
2. TS 中 生命周期的寫(xiě)法
既然是模擬請(qǐng)求,肯定要走鉤子里面寫(xiě)
2.1 首先回顧下 TS當(dāng)中data 的用法
是直接在組件寫(xiě)的
@Options({
props: {
msg: String,
},
})
export default class HelloWorld extends Vue {
msg!: string;
characters:string[] = ["類型注解","編譯性的語(yǔ)言"]
}
2.2 事件的寫(xiě)法
也是在組件中直接寫(xiě)的
addCharacter(e: KeyboardEvent) {}
2.3 鉤子的寫(xiě)法
- 也是直接寫(xiě)的哦
- 所以注意名字不要敲錯(cuò)了,錯(cuò)了就理解成自定義函數(shù)了
// **************生命周期 鉤子
created() {
this.characters = [
{ id: 1, name: "類型注解", selected: true },
{ id: 2, name: "編譯性的語(yǔ)言", selected: false },
];
}
3. 接口類型定義
模擬 數(shù)據(jù)接口
// *********** 泛型 可以是接口 類 ,方法 非常廣泛 的
interface Result<T> {
ok: 0 | 1;
data: T;
}
function getList<T>(): Result<T> {
const data: any = [
{ id: 1, name: "類型注解", selected: true },
{ id: 2, name: "編譯性的語(yǔ)言", selected: false },
];
return{
ok: 1,
data,
};
}
4. 使用接口
4.1 核心代碼
// **************生命周期 鉤子
created() {
this.characters = getList<SelectCharacter[]>().data
}
4.2 拆解分析
1.我們知道數(shù)據(jù)返回的類型,所以這里注解下返回的類型
2.返回的不對(duì),就會(huì)報(bào)錯(cuò)
5. promise模擬異步
5.1 接口修改
function getList<T>(): Promise<Result<T>> {
const data: any = [
{ id: 1, name: "類型注解", selected: true },
{ id: 2, name: "編譯性的語(yǔ)言", selected: false },
];
return Promise.resolve({
ok: 1,
data,
});
}
5.2 簡(jiǎn)要分析
1.整個(gè)返回的結(jié)果用
Promise
包裹一層
2.最終的結(jié)果就像ajax
一樣異步的,用Promise
的resolve
吐出去
6. 接口使用
6.1 簡(jiǎn)要代碼
// **************生命周期 鉤子
async created() {
this.characters = (await getList<SelectCharacter[]>()).data
}
6.2 寫(xiě)法2
async created() {
getList<SelectCharacter[]>().then((result) => {
this.characters = result.data;
});
}
6.3 分析
1.其實(shí)這個(gè)
await
和then
一樣 都是脫去Promise
的一層殼
2.因?yàn)槲覀冊(cè)诙xgetList
的數(shù)據(jù)的時(shí)候里面是用resolve
包裹一層的
3.目前await
和async
聯(lián)合起來(lái)的用法在公司其實(shí)也比較常見(jiàn)
4.整體還是Promise
的用法 脫殼
7. mock假數(shù)據(jù)
7.1 mock配置
vue.config.js
module.exports = {
lintOnSave: false,
devServer:{
open:true,
before(app){
app.get("/api/list",(req,res)=>{
res.json( [
{ id: 1, name: "類型注解", selected: true },
{ id: 2, name: "編譯性的語(yǔ)言", selected: false },
])
})
}
}
}
7.2 重啟
修改了這個(gè)
vue.config.js
文件 需要重啟
8 axios
8.1 環(huán)境
npm i axios 安裝
在需要的文件引入
import Axios from "axios";
8.2 發(fā)請(qǐng)求
// **************生命周期 鉤子
// 怎么用 直接寫(xiě)唄
async created() {
Axios.get<SelectCharacter[]>("/api/list").then(res=>{
this.characters = res.data;
})
}
async await寫(xiě)法
this.characters = (await Axios.get<SelectCharacter[]>("/api/list")).data
8.3 圖示
1.png
參考資料
1.promise
2.TS語(yǔ)法-03
3.TS語(yǔ)法-04