Method to obtain a reference to the current Pinia store: dynamic combination operation
P粉195200437
2023-08-14 14:12:02
<p>This is “roughly” what I want: </p>
<pre class="brush:php;toolbar:false;">// This is a general composable function:
function export useGeneric() {
function genericAct(){
const store = getCurrentStore(); // This is what I need
store.a.value = 42;
store.act2(); // This action should be implemented using a common function in the store
}
return {genericAct}
}
// Here is an example store using it
export const useMyStore = defineStore('myStore', () => {
const a = ref(1);
const b = ref(1);
const {genericAct} = useGeneric();
function act2(){
b.value = 43;
}
return {a, b, genericAct, act2};
}</pre>
<p>How do I get the storage to which this action is bound? (Or how to pass it as an argument to <code>useGeneric</code>?)</p>
<p>(Of course, this is just the simplest example. In practical applications, I will use this to do more useful things...)</p>
I don't know if this is the best approach, you may also consider @Estus Flask's comment:
But I ended up choosing to pass
useMyStore
as a parameter.Please note that it should be called in every generic operation, because when
useGeneric()
is executed, the store has not yet been created.The following is a code example: