安全取值,防止因为 undefined/null 等原因抛出异常,最后一个参数表示如果不存在对应路径得属性时返回的默认值。正常写的话就是:return this.$route.meta.pChild.Create || false;但 meta、meta.pChild、meta.pChild.Create 每一级都有可能不存在导致抛出异常,所以健壮性稍微好一点儿的话就得写成:return this.$route && this.$route.meta && this.$route.meta.pChild && this.$route.meta.pChild.Create || false;但其实这种利用布尔短路的写法是有弊端的,最健壮的写法其实是:// 用嵌套 if 理解起来更容易,你要简写成一坨三元表达式也不是不行 if (this.$route !== undefined && this.$route !== null) { if (this.$route.meta !== undefined && this.$route.meta !== null) { if (this.$route.meta.pChild !== undefined && this.$route.meta.pChild !== null) { if (this.$route.meta.pChild.Create !== undefined && this.$route.meta.pChild.Create !== null) { return this.$route.meta.pChild.Create; } } } } return false;但这写起来多恶心?lodash 就封装了一下。P.S. ES2020 / TS 中可以已经可以利用可选链和双问号操作符这两个新语法优雅地处理了:return this.$route?.meta?.pChild?.Create ?? false;
安全取值,防止因为
undefined/null
等原因抛出异常,最后一个参数表示如果不存在对应路径得属性时返回的默认值。正常写的话就是:
但
meta
、meta.pChild
、meta.pChild.Create
每一级都有可能不存在导致抛出异常,所以健壮性稍微好一点儿的话就得写成:但其实这种利用布尔短路的写法是有弊端的,最健壮的写法其实是:
但这写起来多恶心?lodash 就封装了一下。
P.S. ES2020 / TS 中可以已经可以利用可选链和双问号操作符这两个新语法优雅地处理了: