我想只在数据存在时才向用户显示数据(所以如果他识别)但我去一个错误:无法读取未定义的属性(阅读'email')我不明白,因为我使用了v-if属性来避免这里的错误
<template>
<div>
<Navbar/>
<p v-if="this.$auth.$storage.state.user.email"> {{ this.$auth.$storage.state.user.email }} </p>
</div>
</template>
变量this.$auth.$storage.state.user
为空
如v-if
在email
对象或user
上,则在检查变量之前抛出错误。
所以,我建议你使用这个代码:
<template>
<div>
<p v-if="this.$auth.$storage.state.user">{{ this.$auth.$storage.state.user.email }}</p>
</div>
</template>
实际上,如果您考虑测试用例,它将是这样的this.$auth
将是有效的,但它可能不包含$storage
,所以它可能会抛出一个错误,说不能读取未定义的state
。这同样适用于更深入地检查属性。因此,要在每个阶段进行这种检查,您可以遵循以下方法
<template>
<div>
<p v-if="$auth?.$storage?.state?.user">{{ $auth.$storage.state.user.email }}</p>
</div>
</template>
对于v-if
内部的可选链接,安装@babel/plugin-proposal-optional-chaining并将其添加到babel的配置插件中,如@babel/plugin-proposal-optional-chaining
一个简单的解决方案是
<template>
<div>
<Navbar />
<p v-if="isEmailFilled">
{{ $auth.$storage.state.user.email }}
</p>
</div>
</template>
<script>
export default {
computed: {
isEmailFilled() {
return this.$auth?.$storage?.state?.user?.email
},
},
}
</script>