清空Vuex对象时如何避免Vue项目出现未定义错误?

ale*_*lex 6 javascript vue.js vuejs2

例子。我有一个userVuex 数据,在模板中像这样使用:

// Inside <template>
<button
  v-if="!user.expiredInfo.isExpired"
</button>

// Inside <script>
data () {
 return {
   disable: this.user.expiredInfo.isExpired ? 'text-muted' : '',
 }
}
Run Code Online (Sandbox Code Playgroud)

我有一个执行此操作的操作:

const state = {
  user: {}
}

async logout ({ commit }) {
  commit('SET_USER', {})
},
Run Code Online (Sandbox Code Playgroud)

所以当我注销时出现错误:

TypeError: Cannot read property 'isExpired' of undefined

如何预防此类问题的发生?

Dec*_*oon 3

user当没有登录用户时,您应该设置为 null,而不是尝试使用空对象来避免此类错误。这意味着您始终需要考虑这样一个事实:用户可能实际上并未在模板中的某个点登录,您将在模板中呈现来自(可能不存在)用户对象的一些数据。

您可以执行以下操作来避免此类错误(取决于您想要的逻辑):

<button v-if="user && !user.expiredInfo.isExpired"></button>
<button v-if="!user || !user.expiredInfo.isExpired"></button>
Run Code Online (Sandbox Code Playgroud)

或者,如果您有很多特定于登录的模板,如下所示:

<template v-if="user">
  <!-- It's safe to access properties of the user object anywhere in here -->
</template>
Run Code Online (Sandbox Code Playgroud)

永远不要假设this.user始终为非空(除非这是您强制执行的不变量)。