現象描述
這是 JS 開發中常見的錯誤。對一個值為 null 或 undefined 的變量取屬性就會報錯。例如:
1
2
3
|
<!-- a = {}; -->
<
text
>{{ a.b.c }}</
text
>
<!-- Error: Cannot read property 'c' of undefined -->
|
解決方法
1、&& 方法,通過邏輯運算的執行順序來規避錯誤。代碼如下:
app.ux代碼如下:
1
|
<
text
>{{ a && a.b && a.b.c }}</
text
>
|
2、 在 ViewModel 上增加函數方法
推薦方案 2,在 ViewModel 上建立一個 checkEmpty 函數。示例代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
export
default
{
checkEmpty(...args) {
let ret
if
(args.length > 0) {
ret = args.shift()
let tmp
while
(ret && args.length > 0) {
tmp = args.shift()
ret = ret[tmp]
}
}
return
ret ||
false
}
}
|
這樣,就可以方便的調用了。