Vue3 Composition API的setup中无法获取Vuex异步返回的categories值如何解决
问题原因
核心为异步请求时序不匹配:store.dispatch('categories/getCategories')触发的是异步网络请求,setup执行时接口还未返回结果,Vuex中categories的初始值是空数组,此时直接访问categories.value[selectedItem.value]自然返回undefined。页面可正常渲染是因为computed具备响应式特性,接口返回数据更新Vuex状态后,computed会自动同步新值触发视图重渲染。
解决方案
方案1:使用watch监听响应式数据变化(推荐)
无侵入修改现有逻辑,监听categories和选中项的变化,数据加载完成后自动触发操作,同时支持选中项切换时自动执行对应逻辑:
import { computed, ref, watch } from 'vue' import { useStore } from 'vuex' import Item from '@/components/Item.vue' export default { components: { Item }, setup () { const store = useStore() store.dispatch('categories/getCategories') const categories = computed(() => store.getters['categories/getCategories']) const selectedItem = ref(1) const selectItem = (index) => { selectedItem.value = index } // 新增监听逻辑 watch( [categories, selectedItem], ([newCategories, newSelected]) => { // 边界判断避免下标越界报错 if (newCategories.length > newSelected) { console.log(newCategories[newSelected].id) } }, { immediate: true } ) return { categories, selectedItem, selectItem } } }
方案2:等待异步请求完成后执行
如果仅需要在首次请求完成后执行一次逻辑,可以直接等待dispatch的异步结果返回:
import { computed, ref } from 'vue' import { useStore } from 'vuex' import Item from '@/components/Item.vue' export default { components: { Item }, setup () { const store = useStore() const categories = computed(() => store.getters['categories/getCategories']) const selectedItem = ref(1) const selectItem = (index) => { selectedItem.value = index } // 等待异步请求完成后执行操作 (async () => { await store.dispatch('categories/getCategories') if (categories.value.length > selectedItem.value) { console.log(categories.value[selectedItem.value].id) } })() return { categories, selectedItem, selectItem } } }
两种方案均加入了边界判断,避免接口返回的分类数量小于默认选中下标时再次出现undefined报错。
内容的提问来源于stack exchange,提问作者kasp3rsky
相关产品推荐
相关产品推荐

