Search code examples
vue.jsvuejs3pinia

How do I use a Vue3 Pinia store inside the methods of a component?


I can't seem to find the answer to this simple question. In all the examples and tutorials for the Pinia store, the store is referenced in the setup of a component, and then used in the template part of the component:

<script setup>
  import {useUserStore} from "@/stores/UserStore.js";
  const store = useUserStore();
</script>

<template>
  <h1>{{ store }}</h1>
</template>

This is all good, but if I use the store in a component method and call that method from the template section:

<script>
export default {
  methods:
  {
    methodExample() {
      console.log(store);
    },
  }
}
</script>

I get the error: Uncaught (in promise) ReferenceError: store is not defined.

I can't seem to find a single example where the store is used not in the template part but in the methods of the script part. What am I missing?

Many thanks


Solution

  • for example, through the use of computed:

    <script>
    import {useUserStore} from "@/stores/UserStore.js";
    
    export default {
      computed: {
        store: () => useUserStore();
      }, 
      methods:
      {
        methodExample() {
          console.log(this.store);
        },
      }
    }
    </script>