我正在用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 || [];
},