I can't find a way to apply a plugin only to specific store. #2027
-
|
In the doc, it says |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 2 replies
-
|
Hm, if I get you clear you just need to compare const id = 'yourId'
pinia.use(({ store }) => {
if(store.$id === id) {
....
}) |
Beta Was this translation helpful? Give feedback.
-
|
This method would not work for me at all. to load an imported plugin. But I used the same conditional at the top of the actual plugin for an early return and it works. As for Typescript autocompletion I have the opposite problem. Even before restricting the plugin to the one store, the plugin methods were missing from the stores type. I had to create a custom type in the template where I want to use the plugin methods. import { useProductStore, useCartStore } from '~/stores';
const productStore = useProductStore();
const cartStore = useCartStore();
export type CartStoreWithPlugin = typeof cartStore & {
undoHistory: () => void;
redoHistory: () => void;
};
const store = cartStore as CartStoreWithPlugin; |
Beta Was this translation helpful? Give feedback.
-
|
Found this page via search on the web so leaving my solution here for others. To use a specific store inside the pinia plugin, you can create a type guard, to avoid any import type { PiniaPlugin } from "pinia";
import type { useMyStore } from "./myStore";
type MyStore = ReturnType<typeof useMyStore>;
// TS type guard
function isMyStore(store: { $id: string }): store is MyStore {
return store.$id === "my-store";
}
const myPlugin: PiniaPlugin = ({ store }) => {
if (!isMyStore(store)) return;
// store is fully typed as MyStore, no cast needed
store.myAction();
};Thanks for the earlier answers! They helped so I could make it work. |
Beta Was this translation helpful? Give feedback.
Hm, if I get you clear you just need to compare
store.$idwith id of the store you need to patch.Like this: