Pinia中无法访问getter函数的值:可见值但获取为null
解决Pinia Getter能在控制台看到值但访问时为null的问题
问题根源
你遇到的是异步操作时序问题:
- 调用
getProducts后,会先把pro.value设为null,再发起axios异步请求 - 当你立刻访问
getProductList时,请求还未完成,pro.value仍然是null - 控制台能看到值是因为浏览器的特性:对于数组/对象这类引用类型,控制台会在你展开时显示内存中的最新值,而非你访问那一刻的快照值
解决方案
方案1:让getProducts返回Promise,确保请求完成后再访问数据
修改Store中的getProducts为异步函数:
const pro = ref() const getProductList = computed(() => pro.value) const getProducts = async (val1 = 'newest', val2 = '', val3 = 0, val4 = 0, val5 = 0, val6 = '', val7) => { pro.value = null try { const res = await axios.get('', { params: { sort: val1, title: val2, flash_id: '', max_price: val3, min_price: val4, available: val5, category_id: val6, vip: 0, attribute_value_id: [val7] } }) pro.value = res.data.data.products console.log(pro.value) } catch (err) { console.log(err) } }
组件中调用时用await等待请求完成:
// 组件内 async function fetchProducts() { await store.getProducts(/* 传入你的参数 */) // 此时访问getProductList即可拿到数据 console.log(store.getProductList) }
方案2:添加加载状态,组件中根据状态判断
在Store中新增加载状态:
const pro = ref() const isLoading = ref(false) const getProductList = computed(() => pro.value) const getProducts = (val1 = 'newest', val2 = '', val3 = 0, val4 = 0, val5 = 0, val6 = '', val7) => { isLoading.value = true pro.value = null axios.get('', { params: { sort: val1, title: val2, flash_id: '', max_price: val3, min_price: val4, available: val5, category_id: val6, vip: 0, attribute_value_id: [val7] } }) .then((res) => { pro.value = res.data.data.products console.log(pro.value) }) .catch(err => { console.log(err) }) .finally(() => { isLoading.value = false }) }
组件模板中根据状态渲染:
<template> <div v-if="store.isLoading">加载中...</div> <div v-else> <!-- 这里可以安全访问store.getProductList --> </div> </template>
方案3:监听getProductList的变化
组件中用watch监听数据变化,值非空时再处理:
// 组件内 import { watch } from 'vue' watch(() => store.getProductList, (newVal) => { if (newVal) { // 数据已加载完成,在这里处理业务逻辑 console.log(newVal) } }, { immediate: true })
内容的提问来源于stack exchange,提问作者Saeed
相关产品推荐
相关产品推荐

