Home  >  Q&A  >  body text

Method to obtain a reference to the current Pinia store: dynamic combination operation

<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>
P粉195200437P粉195200437455 days ago529

reply all(1)I'll reply

  • P粉106715703

    P粉1067157032023-08-15 12:45:05

    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:

    // 这是一个通用的可组合函数:
    function export useGeneric(getStore:any) { // 这里的类型定义非常困难,也许使用接口来避免使用 any 是最好的解决方案
      function genericAct(){
        const store = getStore(); // 这就是我需要的
        store.a.value = 42;
        store.act2(); // 这个操作应该在 store 中使用泛型来实现
      }
      return {genericAct}
    }
    
    // 这是一个使用它的示例 store
    export const useMyStore = defineStore('myStore', () => {
      const a = ref(1);
      const b = ref(1);
      const {genericAct} = useGeneric(useMyStore);
      function act2(){
        b.value = 43;
      }
      return {a, b, genericAct, act2};
    }

    reply
    0
  • Cancelreply