如何捕获一个空的Vuex Store状态,但在初始化时有一个计算属性对它做出反应



我正在用Vuex做一个Vue店面项目。

我有以下元素排序产品在我的网店

<SfSelect
class="navbar__select sort-by"
ref="SortBy"
:selected="selectedSorting"
@change="setSortingAttribute"
>
<SfSelectOption
v-for="attribute in getSortingAttributes"
:key="attribute.id"
:value="attribute.title"
class="sort-by__option"
@click="setSelectedSortingAttribute(attribute)"
>
{{ attribute.title }}
</SfSelectOption>
</SfSelect>

其中v-for="attribute in getSortingAttributes"对所有可用的过滤器执行for循环。

这些过滤器通过以下计算属性从Vuex Store状态调用:

getSortingAttributes: function () {
if (store.state.tweakwise.tweakwiseLayeredNavigationAttributes
.properties.sortfields
) {
var tempSortAttributes =
this.$store.state.tweakwise.tweakwiseLayeredNavigationAttributes
.properties.sortfields;
return tempSortAttributes;
}
},

这个数组在Vuex Store (tweakwiseLayeredNavigationAttributes.properties.sortfields)中,其中.properties是数组中的一个对象。数组是通过API调用填充的,这个调用是通过与SfSelect函数相同的类中的Mount()触发的,我在上面提到过。

尽管我在getSortingAttributes中添加了if-statement以防止它调用未定义的数据,并使其成为计算属性(在数据可用时立即调用它),我仍然得到以下错误:

渲染时出错:CategoryX/SubcategoryY/

TypeError: Cannot read property 'sortfields' of undefined

您应该在代码中添加保护措施—使用新的空合并操作符或老式布尔or:

getSortingAttributes() 
{
return this.$store.state.tweakwise?.tweakwiseLayeredNavigationAttributes?.properties?.sortfields || [];
},
getSortingAttributes() 
{
return (((this.$store.state.tweakwise || {}).tweakwiseLayeredNavigationAttributes || {}).properties || {}).sortfields || [];
},

相关内容

最新更新