Vue+Inertia+Laravel中如何用if/else判断InertiaRequest props是否为空
问题:Vue组件v-if判断Inertia props为空时抛出类型错误
在Vue组件中用v-if判断从HandleInertiaRequest接收的props是否为空时,props不为空时正常,但为空时会抛出以下错误:
Navbar.vue:66 Uncaught (in promise) TypeError: Cannot read properties of null (reading 'name') at Proxy._sfc_render (Navbar.vue:66:46) at renderComponentRoot (runtime-core.esm-bundler.js:816:16) at ReactiveEffect.componentUpdateFn [as fn] (runtime-core.esm-bundler.js:5701:46) at ReactiveEffect.run (reactivity.esm-bundler.js:178:19) at instance.update (runtime-core.esm-bundler.js:5814:51) at setupRenderEffect (runtime-core.esm-bundler.js:5822:5) at mountComponent (runtime-core.esm-bundler.js:5612:5) at processComponent (runtime-core.esm-bundler.js:5565:9) at patch (runtime-core.esm-bundler.js:5040:11) at mountChildren (runtime-core.esm-bundler.js:5284:7)
原本的v-if写法:
<div v-if="$page.props.auth.user.name"> <p>{{ $page.props.auth.user.name }}</p> </div> <div v-else> <Link :href="route('login')"> <p class="btn btn-ghost">Sign in</p> </Link> </div>
尝试用isset方法也报错,代码如下:
<div v-if="isset($page.props.auth.user.name)"> <p>{{ $page.props.auth.user.name }}</p> </div> <div v-else> <Link :href="route('login')"> <p class="btn btn-ghost">Sign in</p> </Link> </div>
解决方案
1. 使用可选链操作符(?.)
这是最简洁的解决方式,通过?.操作符可以安全访问嵌套属性,只要前面的属性为null或undefined,就会停止后续访问,不会抛出错误。修改后的代码:
<div v-if="$page.props.auth?.user?.name"> <p>{{ $page.props.auth.user.name }}</p> </div> <div v-else> <Link :href="route('login')"> <p class="btn btn-ghost">Sign in</p> </Link> </div>
2. 逐层判断属性存在性
如果项目环境不支持可选链(现在大部分Vue项目都支持),可以逐层判断每个嵌套对象是否存在:
<div v-if="$page.props.auth && $page.props.auth.user && $page.props.auth.user.name"> <p>{{ $page.props.auth.user.name }}</p> </div> <div v-else> <Link :href="route('login')"> <p class="btn btn-ghost">Sign in</p> </Link> </div>
3. 注意:Vue中没有isset方法
你尝试的isset是PHP的内置方法,JavaScript(Vue)里不存在这个全局方法,所以调用它会直接报错,不要在Vue代码中使用这个方法。
内容的提问来源于stack exchange,提问作者cherno304
相关产品推荐
相关产品推荐

