I am using pinia and vue-router 4.x ,but i am having a problem using both of them in a store. each works independently ,but not together.
If i use
import router from '../router'
router will work but pinia is failed with error
Uncaught ReferenceError: Cannot access 'useAuthStore' before initialization
at axiosroot.ts
@line let authStore = useAuthStore(pinia);
//here is axiosroot.ts
import axios from "axios";
import {useAuthStore} from '../stores/auth-store'
import { createPinia } from "pinia";
const pinia=createPinia();
let authStore = useAuthStore(pinia);
const url = "http://127.0.0.1:8000/api";
const myToken =authStore.getToken;
export default axios.create({
url,
headers:{"Accept":"application/json"},
});
When i import router from vue-routern useRouter
is undefined
import {useRouter} from 'vue-router'
const router =useRouter();
the error
Uncaught TypeError: Cannot read properties of undefined (reading 'push')
---
error @ line router.push({name:'Login'})
// here is the remainning relavant code
import { defineStore, acceptHMRUpdate } from "pinia";
//import router from '../router'
import {useRouter} from 'vue-router'
const router =useRouter();
export const useAuthStore = defineStore({
id: "user",
actions: {
LogOut(payload) {
// this.DELETE_TOKEN(null);
// this.UPDATE_LOGIN_STATUS(false);
router.push({name:'Login'})
},
},
});
Router has to be used as a plugin in pinia. I read this in the pinia.documentation https://pinia.vuejs.org/core-concepts/plugins.html
When adding external properties, class instances that come from other libraries, or simply things that are not reactive, you should wrap the object with markRaw() before passing it to pinia. Here is an example adding the router to every store:
import { markRaw } from 'vue'
// adapt this based on where your router is
import { router } from './router'
pinia.use(({ store }) => {
store.router = markRaw(router)
})
This will add pinia to every store you create. The config in main.ts is the same as for vue plugins.
import { createApp, markRaw } from 'vue';
import { createPinia } from 'pinia';
import App from './app/App.vue';
import { router } from './modules/router/router';
const app = createApp(App);
const pinia = createPinia();
pinia.use(({ store }) => {
store.$router = markRaw(router)
});
app.use(router)
Now you can access router in your stores.
export const useMyStore = defineStore("myStore", {
state: () => {
return {};
},
actions: {
myAction() {
this.$router.push({ name: 'Home' });
},
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With