How to composable with reusable composition functions #454
-
I have a scenario where multiple pages need to reuse the same table logic. Example: |
Beta Was this translation helpful? Give feedback.
Answered by
posva
May 17, 2021
Replies: 2 comments 1 reply
-
You should accept a ref as a parameter and pass in a ref of the store state: export function useTable(apiUrl: string, stateRef?: Ref<{ total: number, query: Record<string, any>, list: string[] }) {
const state = ref<{
total: number;
query: Record<string, any>;
list: string[];
// the ref() will reuse the passed ref if it's a ref already, without creating a new one
}>(stateRef || {
total: 0,
query: {
page: 1,
size: 10,
},
list: [],
});
function fetchList() {
state.value.total = 100;
state.value.list = [];
}
function resetQuery() {
state.value.query = {
page: 1,
size: 10,
};
}
return {
state,
fetchList,
resetQuery,
};
} and then use it with your store const useStore = defineStore({
id: 'table',
state: () => ({ table: {
// ...
}})
const store = useStore()
useTable('/api/table', toRef(store, 'table') |
Beta Was this translation helpful? Give feedback.
1 reply
-
I've fixed some bugs and updated the docs about how to add refs to the store: https://pinia.esm.dev/core-concepts/plugins.html#adding-new-state |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
posva
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I've fixed some bugs and updated the docs about how to add refs to the store: https://pinia.esm.dev/core-concepts/plugins.html#adding-new-state