取得目前 Pinia store 的引用的方法:動態組合操作
P粉195200437
P粉195200437 2023-08-14 14:12:02
0
1
484
<p>這是我想要的「大致」內容:</p> <pre class="brush:php;toolbar:false;">// 這是一個通用的可組合函數: function export useGeneric() { function genericAct(){ const store = getCurrentStore(); // 這是我需要的 store.a.value = 42; store.act2(); // 這個動作應該在儲存中使用通用函數實現 } return {genericAct} } // 這是一個使用它的範例存儲 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>我如何取得綁定了該動作的儲存? (或如何將它傳遞為<code>useGeneric</code>的參數?)</p> <p>(當然,這只是一個最簡單的範例。在實際應用中,我會用這個做更多有用的事情...)</p>
P粉195200437
P粉195200437

全部回覆(1)
P粉106715703

我不知道這是否是最好的方法,你也可以考慮 @Estus Flask 的評論:

但我最終選​​擇將 useMyStore 作為參數傳遞。

請注意,它應該在每個通用操作中調用,因為在 useGeneric() 執行時,store 尚未建立。

下面是程式碼範例:

// 这是一个通用的可组合函数:
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};
}
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!