Neidi
Neidi

Reputation: 116

How does pinia (Vue.js) determines the correct pinia instance to use

this is a theoretical question with the goal of understanding how Pinia works under the hood.

According to this page, I can use useFooStore() anywhere in my app, even outside of components, as long as I call useFooStore() after I called app.use(pinia) or setActivePinia(pinia). (This doesn't apply in case of SSR, but my question refers to using it inside the browser).

I don't understand, how "useFooStore()" determines the correct Pinia instance. I could imagine that the pinia is resolved over the Vue app instance but how does "useFooStore" has access to the Vue instance?

Consider the following sitiation (not tested. Does this even work?):

  1. One uses Compostion API
  2. There are two Vue instances
  3. Both Vue instances have their own pinia instance
  4. A Component of "Vue Instance A" uses the "foo" store by calling foo = "useFooStore()"
  5. A Component of "Vue Instance B" uses the "foo" store by calling foo = "useFooStore()"

How does the module "useFooStore.js" figures out the correct pinia? I know, that the component instance has access to the vue instance it's running inside, but "useFooStore" doesn't has access to the component neither lexical nor through "this". How is this possible in JS???

Or is the pinia instance set globally (similar to the singleton design pattern) and it is just assumed, that there is just one Vue Instance. It seems strange, that this is not mentioned anywhere if thats the case...

Upvotes: 0

Views: 1390

Answers (1)

Jishan Shaikh
Jishan Shaikh

Reputation: 1806

When you use the app.use() method to install a plugin in Vue, that plugin scope becomes the installed Vue instance's scope. useFooStore() will have access to the correct instance of Pinia because it is called within the context.

In the situation described, it would not be possible for a component on one Vue instance to access the stores from a different instance of Pinia, they are isolated (context-bounded). Vue does not have a global singleton instance, so if you want to use multiple instances of Vue in the same app, you will have to create/manage those by yourself.

Upvotes: 0

Related Questions