这是 JS 开发中常见的错误。对一个值为 null 或 undefined 的变量取属性就会报错。例如:
<!-- a = {}; -->
<text>{{ a.b.c }}</text>
<!-- Error: Cannot read property 'c' of undefined -->
1 、&& 方法,通过逻辑运算的执行顺序来规避错误。代码如下:
app.ux代码如下:
<text>{{ a && a.b && a.b.c }}</text>
2 、 在 ViewModel 上增加函数方法
推荐方案 2 ,在 ViewModel 上建立一个 checkEmpty 函数。示例代码如下:
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
}
}
这样,就可以方便的调用了。
<text>{{checkEmpty(a, 'b', 'c')}}</text>
原文链接: https://developer.huawei.com/consumer/cn/forum/topic/0201454975951760782?fid=0101271690375130218
原作者:Mayism
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69970551/viewspace-2782389/ ,如需转载,请注明出处,否则将追究法律责任。