Home > Software engineering >  Can't access Pinia store in beforeEnter in vue 2 app
Can't access Pinia store in beforeEnter in vue 2 app

Time:12-21

I am using Pinia in a vue 2 app, and am trying to access some state in the beforeEach route guard, but receive the following error:

pinia error

I've followed the documentation here: https://pinia.vuejs.org/core-concepts/outside-component-usage.html, but I continue to get the same error.

I've also tried importing the pinia instance and providing it to useAppStore in beforeEach, but that doesn't seem to help either.

routes/index.js

import VueRouter from "vue-router";
import AlertInbox from '@/views/AlertInbox/main';
import AlertForm from '@/components/AlertForm/main';
import TextMessageForm from '@/components/TextMessageForm/main';
import AlertDetails from '@/views/AlertDetails/main';
import AlertSearch from '@/views/AlertSearch/main';
import AlertType from '@/components/AlertType/main';
import MMApp from '@/components/App/main';
import { useAppStore } from '@/stores/AppStore';

Vue.use(VueRouter);


const routes = [
  {
    path: '/',
    component: MMApp,
    children: [
      {
        path: 'alert',
        name: 'alertForm',
        component: AlertForm,
      },
      {
        path: 'alert/:id',
        component: AlertDetails,
        props: true,
        children: [
          {
            name: 'alertDetails',
            path: '',
            component: AlertType,
          }
        ]
      },
      {
        path: 'text-message',
        name: 'textMessageForm',
        component: TextMessageForm,
        props: route => ({ customerId: route.query.customer })
      },
      {
        path: 'search/alerts',
        name: 'alertSearch',
        component: AlertSearch,
      },
      {
        path: ':filter',
        name: 'inbox',
        component: AlertInbox,
      },
    ]
  },
];

const router = new VueRouter({
  base: "/",
  mode: "history",
  routes,
});

router.beforeEach(() => {
  const store = useAppStore();
  console.log(store.counts);
});

export default router;

main.js

import Vue from "vue";
import { createPinia, PiniaVuePlugin } from "pinia";

import App from "./App.vue";

import VueCompositionAPI from "@vue/composition-api";
Vue.use(VueCompositionAPI);

Vue.config.productionTip = false;

Vue.use(PiniaVuePlugin);
const pinia = createPinia();

import router from "./router";


new Vue({
  router,
  pinia,
  render: (h) => h(App),
}).$mount("#app");

export default pinia;

CodePudding user response:

Add Vue.use(pinia); after const pinia = createPinia();

  • Related