pinia 存储的多个实例可以在同一页面或同一组件中吗?

问题描述 投票:0回答:3

我有一家 pinia 商店,是产品商店。我在产品页面中使用它来获取产品列表。我还在该页面的隐藏弹出框中使用它,这是产品创建组件。

当我在 create-product 组件中调用 pinia 操作 fetchProductsList(cat1) 时,它会获取 cat1 的产品。但它也会改变产品页面中产品的结果。

我想在产品页面和产品创建组件上使用不同的产品商店实例来获得不同的产品结果。但我得到了同样的结果。

有什么方法可以在同一页面中创建同一 pinia 商店的不同实例,以便我可以根据我的需要为 ProductStore.products 获得不同的结果??

    import { defineStore } from 'pinia'
    
    export const useProductsStore = defineStore('products', {
    
        state: () =>
         ({ 
           
           products: [],
    
           
         }),
    
        getters: {
            getProducts: state => state.products
        },
    
        actions: {
    
            async fetchProductsList(category){
    
                return new Promise((resolve,reject)=>{
    
                    axios.get(`/api/products?product_cat=${category}`)
                    .then((response) => { 
                        this.products = response.data 
                        resolve(response)
                    })
                    .catch((errors)=>{
                        reject(errors)
                    })
                })
                       
            },
    
          
        },

})
vuejs3 pinia
3个回答
0
投票

我认为您没有正确使用 pinia。存储包含在组件之间共享的状态,因此它应该只有一个实例。就您而言,我认为您应该创建另一个用于

CreateProduct
组件的商店。该存储可能包含状态
newProducts
和 getter
allProducts
,它们由
products
ProductStore
中的
newProducts
组合而成。


0
投票

Posva(Pinia 的创建者)建议这样做这里

const options = {}
defineStore('one', {...options})
defineStore('two', {...options})

0
投票

要使用同一商店的多个实例但不共享引用(状态属性),您可以这样做:

这个例子在Vue“Composition API: setup()”中

import { computed, ref } from 'vue'
import { defineStore } from 'pinia'

const myStore = () => {
  const myRef = ref('A ref is a state property')
  const myGetter = computed(() => 'computed is a getter')
  
  return {
    myRef,
    myGetter,
  }
}

export const useMyStore = (uniqueStoreName) => {
  let store = defineStore(uniqueStoreName, myStore)
  return new store()
}

export default useMyStore

然后在你的组件中使用它和唯一的名称

<template></template>
<script setup>

import { storeToRefs } from 'pinia'
import useMyStore from '~/stores/myStore'

const props = defineProps({
  distinctiveStoreName: {
    type: String,
    required: false,
    default: () =>
      'every-component-needs-a-unique-store-name-if-you dont-want-to-share-the-state-refs',
  },
})

const myStore = useMyStore(props.distinctiveStoreName)
const {
  // Some refs from the store
} = storeToRefs(myStore)

// Use getters from the store
let value = myStore.myGetter

</script>
© www.soinside.com 2019 - 2024. All rights reserved.