在 Vue 3 中使用 Pinia 作为状态管理库时,如果尝试通过解构赋值的方式来获取 Pinia store 中的状态,并期望这些解构出来的变量保持响应性,可能会遇到响应性丢失的问题。这是因为解构赋值本质上会创建原始数据的浅拷贝,而这些拷贝并不是响应式的。

解决方案

1. 使用 storeToRefs

定义 Store | Pinia (vuejs.org)

storeToRefs 是 Vue 3 Composition API 中的一个函数,用于将 Pinia store 中的状态转换为响应式引用。这样,即使你通过解构赋值获取了状态,这些状态仍然是响应式的。

import { defineComponent } from 'vue';  
import { useStore } from './stores/yourStore';  
import { storeToRefs } from 'vue';  
  
export default defineComponent({  
  setup() {  
    const store = useStore();  
    const { someState, anotherState } = storeToRefs(store);  
  
    // 现在 someState 和 anotherState 是响应式的  
    return {  
      someState,  
      anotherState,  
    };  
  },  
});
2. 使用 computed 或 watch

如果需要基于 store 中的状态计算新值,或者需要监听这些状态的变化,你可以使用 Vue 的 computed 或 watch。虽然这不是直接解决解构赋值响应性丢失的问题,但它提供了另一种处理响应性数据的方式。

import { defineComponent, computed } from 'vue';  
import { useStore } from './stores/yourStore';  
  
export default defineComponent({  
  setup() {  
    const store = useStore();  
  
    // 使用 computed 来基于 store 状态计算新值  
    const computedValue = computed(() => {  
      return store.someState + 1;  
    });  
  
    return {  
      computedValue,  
    };  
  },  
});
3. 直接访问 Store 属性

如果不涉及解构赋值,而只是简单地在模板或计算属性中直接访问 store 的属性,那么这些属性自然是响应式的。

<template>  
  <div>{{ store.someState }}</div>  
</template>  
  
<script>  
import { defineComponent } from 'vue';  
import { useStore } from './stores/yourStore';  
  
export default defineComponent({  
  setup() {  
    const store = useStore();  
  
    return {  
      store,  
    };  
  },  
});  
</script>

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐