【发布时间】:2018-06-16 23:39:16
【问题描述】:
在我的挂载中,我调用 axios 来获取配置文件数据,然后如果成功,我将有效负载发送到“set_account”vuex。
为了恢复这些数据,我在计算中使用 MapGetters (currentAccount)。
当您恢复此数据时,例如:控制台中的 currentAccount.profile.name 我收到:TypeError: Cannot read property 'name' of undefined
但我收到数据。为什么会出现这个错误?
App.vue
<template>
<!-- Don't drop "q-app" class -->
<div id="q-app">
<q-layout ref="layout">
<!-- Header -->
<q-toolbar slot="header" v-if="this.$route.path !== '/'">
<q-btn flat @click="$refs.layout.toggleLeft()">
<q-icon name="menu" />
</q-btn>
<q-toolbar-title>
Saúde Digital
<span slot="subtitle">Meu Perfil</span>
</q-toolbar-title>
</q-toolbar>
<!-- Left Side Panel -->
<div slot="left">
<q-list no-border link inset-separator>
<q-list-header>
Olá: {{currentAccount.profile.name}}.
<q-icon name="sentiment_very_satisfied"/>
</q-list-header>
<q-side-link item to="/docs">
<q-item-side icon="link" />
<q-item-main label="Link" sublabel="Some menu link" />
</q-side-link>
<q-item @click="logout">
<q-item-side icon="power_settings_new" />
<q-item-main label="Logout" />
</q-item>
</q-list>
</div>
<!-- sub-routes get injected here: -->
<router-view />
<!-- Footer -->
</q-layout>
</div>
</template>
<script>
import {http} from 'src/http/index'
import {mapGetters} from 'vuex'
export default {
name: 'app',
beforeMount () {
this.getProfile()
},
computed: {
...mapGetters({
showErros: 'getErrors',
currentAccount: 'currentAccount'
})
},
methods: {
getProfile () {
http.get('profile')
.then(response => {
this.$store.dispatch('set_account', response.data)
})
.catch(error => console.log(error))
},
// If not have localStorage token and path not "/" (login)
// redirect to root (login)
logout () {
this.emptyLocalStorage()
this.$store.dispatch('remove_user')
this.$router.go('/')
},
emptyLocalStorage () {
delete localStorage.token
}
}
}
</script>
Vuex 商店:Auth.js
export default {
state: {
account: false,
errors: false
},
getters: {
currentAccount (state) {
return state.account
},
getErrors (state) {
return state.errors
}
},
mutations: {
LOAD_ERRORS (state, payload) {
state.errors = payload
},
LOAD_ACCOUNT (state, payload) {
state.account = payload
},
REMOVE_ACCOUNT (state, payload) {
state.account = null
}
},
actions: {
set_errors ({commit}, payload) {
commit('LOAD_ERRORS', payload)
},
set_account ({commit}, payload) {
commit('LOAD_ACCOUNT', payload)
},
remove_account ({commit}) {
commit('REMOVE_ACCOUNT')
}
}
}
【问题讨论】:
-
当
mounted出现时,currentAccount.profile.name可能还不存在——此时currentAccount仍然是您在其上设置的字符串'currentAccount'。此字符串没有属性profile。尝试访问未定义的name... -
所以将
data函数中currentAccount的初始值改为{ currentAccount: { profile: { name: null } } } -
我在下面创建了一个级别,例如:
state: { account: { profile: {} }感谢您的解释。解决了。 -
你也可以在绑定中做:
{{ currentAccount.hasOwnProperty('profile') && currentAccount.profile.hasOwnProperty('name') ? currentAccount.profile.name : '' }}
标签: javascript vue.js axios vuex