$mol
搜尋
⌘ K
文件
遊樂場
比較
生態系統
關於
ZH_HK
資料獲取
Getting Started
介紹
心智模型
快速開始
從 TypeScript 到 view.tree
專案結構
工具鏈
Essentials
安裝
視圖
狀態與響應式
路由
渲染
測試
部署
疑難排解
Data
資料獲取
資料模式
Giper Baza
More
展示
來自 React、Vue 和 Svelte
食譜
Advanced
外掛
模組元資料
離線
幽靈視圖
About
常見問題
團隊
發布
API
$mol_button_major
$mol_button_minor
$mol_string
$mol_number
$mol_text
$mol_paragraph
$mol_list
$mol_row
$mol_link
$mol_check
$mol_switch
$mol_select
$mol_scroll
$mol_page
$mol_pick
資料獲取
在 $mol 中載入遠端資料並不是一個特殊的 API——非同步值只是一個寫起來就像回應已經擺在那裏的響應式屬性。視圖會等待它,顯示載入狀態,並在資料到達時重新渲染。
非同步屬性
在
@ $mol_mem
內部發出網絡呼叫,並回傳解析後的結果。程式碼裏沒有 promise,沒有
await
,也沒有回呼:
1
namespace
$
.
$$
{
2
export class
$my_users
extends
$
.
$my_users
{
3
@ $mol_mem
4
users
(
)
{
5
return
this
.
$
.
$mol_fetch
.json
(
'https://api.example.com/users'
)
as
{
6
id:
number
7
name:
string
8
}
[
]
9
}
10
}
11
}
$mol_fetch
會暫停纖程,直到回應到達,隨後這次計算重啟,
users
(
)
回傳那個陣列。在它處於暫停狀態時,任何讀取
users
(
)
的視圖都會自動顯示內建的載入狀態——你無需編寫
isLoading
旗標。不要自己從
@ $mol_mem
回傳一個 promise:被當作值存進單元的 promise 會讓這個單元永遠停在載入狀態,參見
疑難排解
。
this
.
$
是元件的上下文。每一個服務都經由它而來:管網絡的
$mol_fetch
、管 URL 的
$mol_state_arg
、管時間的
$mol_after_timeout
。在測試裏上下文會被換掉,於是同一個
users
(
)
會把請求發給一個 mock 而不是網絡,元件本身一行都不用改。
測試
展示了那個 mock。
渲染結果
把解析後的資料直接綁定到列表中:
1
@ $mol_mem
2
user_names
(
)
{
3
return
this
.users
(
)
.map
(
user
=
>
user
.
name
)
4
}
當回應到達時,
users
(
)
更新,
user_names
(
)
重新計算,列表隨之渲染。沒有回呼,沒有
useEffect
。
重新載入
因為它只是一個響應式單元,你透過使其失效來重新獲取。依賴一個你可以自增的權杖:
1
@ $mol_mem
2
reload_token
(
next
?
:
number
)
{
3
return
next
?
?
0
4
}
5
6
@ $mol_mem
7
users
(
)
{
8
this
.reload_token
(
)
// subscribe
9
return
this
.
$
.
$mol_fetch
.json
(
'https://api.example.com/users'
)
as
unknown
[
]
10
}
11
12
@ $mol_action
13
reload
(
)
{
14
this
.reload_token
(
this
.reload_token
(
)
+
1
)
15
}
在 GitHub 上編輯此頁
這有幫助嗎?
是
否
上一頁
疑難排解
下一頁
資料模式
本頁內容
非同步屬性
渲染結果
重新載入
錯誤
下一步
Type to search the documentation.