在存储被 API 调用填充之前出现未定义的 属性 错误
Undefined property error before store gets populated by API call
在我的子组件中,我试图访问存储状态对象(称为 template
)的嵌套 属性(称为 background_color
):
<template>
<div
class="btn"
:style="{ 'background-color': backgroundColor }"
>
content
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState({
backgroundColor: state => state.template.button_branding.secondary_button.background_color
})
}
}
</script>
商店通过商店操作调用从父视图组件填充:
created () {
this.initializeStore()
},
在我的店里,这个动作是这样定义的:
export const actions = {
initializeStore ({ state, commit }, data) {
this.$axios.get('path.to.api.endpoint')
.then((res) => {
commit('setConfig', res.data) // populates store
}).catch((error) => {
console.log(error)
})
}
}
我收到这个错误:
Cannot read property 'secondary_button' of undefined
但我看到我的嵌套 属性 通过 Vue DevTools 填充在状态中。
如何避免这个错误?
您可以结合使用可选链接和无效合并来添加默认值,如下所示:
backgroundColor: state => state.template?.button_branding?.secondary_button?.background_color ?? 'default_value'
这应该可以防止调用 API 时出错。
此外,将您的逻辑移动到商店内的 getter
并在那里设置默认值可能会更整洁:
getters: {
backgroundColor: state => {
return state.template?.button_branding?.secondary_button?.background_color ?? 'default_value'`;
}
}
这样组件就可以使用 mapGetters
并且不需要关心是否使用默认值。
在我的子组件中,我试图访问存储状态对象(称为 template
)的嵌套 属性(称为 background_color
):
<template>
<div
class="btn"
:style="{ 'background-color': backgroundColor }"
>
content
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState({
backgroundColor: state => state.template.button_branding.secondary_button.background_color
})
}
}
</script>
商店通过商店操作调用从父视图组件填充:
created () {
this.initializeStore()
},
在我的店里,这个动作是这样定义的:
export const actions = {
initializeStore ({ state, commit }, data) {
this.$axios.get('path.to.api.endpoint')
.then((res) => {
commit('setConfig', res.data) // populates store
}).catch((error) => {
console.log(error)
})
}
}
我收到这个错误:
Cannot read property 'secondary_button' of undefined
但我看到我的嵌套 属性 通过 Vue DevTools 填充在状态中。
如何避免这个错误?
您可以结合使用可选链接和无效合并来添加默认值,如下所示:
backgroundColor: state => state.template?.button_branding?.secondary_button?.background_color ?? 'default_value'
这应该可以防止调用 API 时出错。
此外,将您的逻辑移动到商店内的 getter
并在那里设置默认值可能会更整洁:
getters: {
backgroundColor: state => {
return state.template?.button_branding?.secondary_button?.background_color ?? 'default_value'`;
}
}
这样组件就可以使用 mapGetters
并且不需要关心是否使用默认值。