无法在单个商店内使用 vue-router 和 pinia

Sey*_*eyT 24 javascript vue.js vue-router pinia

我正在使用 pinia 和 vue-router 4.x ,但我在商店中使用它们时遇到问题。每个都独立工作,但不能一起工作。

如果我使用

import router from '../router'
Run Code Online (Sandbox Code Playgroud)

路由器可以工作,但 pinia 失败并出现错误

Uncaught ReferenceError: Cannot access 'useAuthStore' before initialization
at axiosroot.ts

@line let authStore = useAuthStore(pinia);
Run Code Online (Sandbox Code Playgroud)

//这里是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"},
  
});
Run Code Online (Sandbox Code Playgroud)

当我从 vue-router 导入路由器时useRouter未定义

import {useRouter} from 'vue-router'
const router =useRouter();
Run Code Online (Sandbox Code Playgroud)

错误

Uncaught TypeError: Cannot read properties of undefined (reading 'push') 
--- 
error @ line router.push({name:'Login'})
Run Code Online (Sandbox Code Playgroud)

// 这是剩余的相关代码


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'})
   },
 },
});
Run Code Online (Sandbox Code Playgroud)

小智 31

路由器必须作为 pinia 中的插件使用。我在 pinia.documentation https://pinia.vuejs.org/core-concepts/plugins.html中读到了这个

添加外部属性、来自其他库的类实例或简单的非反应性内容时,您应该在将对象传递给 pinia 之前使用 markRaw() 包装该对象。以下是将路由器添加到每个商店的示例:

import { markRaw } from 'vue'
// adapt this based on where your router is
import { router } from './router'

pinia.use(({ store }) => {
  store.router = markRaw(router)
})
Run Code Online (Sandbox Code Playgroud)

这会将 pinia 添加到您创建的每个商店中。main.ts 中的配置与 vue 插件相同。

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)
Run Code Online (Sandbox Code Playgroud)

现在您可以访问商店中的路由器。

export const useMyStore = defineStore("myStore", {
  state: () => {
    return {};
  },
  actions: {
    myAction() {
      this.$router.push({ name: 'Home' }); 
  },
});

Run Code Online (Sandbox Code Playgroud)


Unu*_*Sec 8

在main.js中:

import { createApp, markRaw } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'

const pinia = createPinia()
pinia.use(({ store }) => {
store.router = markRaw(router)
})
const app = createApp(App)

app.use(pinia)
app.use(router) 
app.mount('#app')
Run Code Online (Sandbox Code Playgroud)

在您的商店中推送路线:

this.router.push({ name: 'home' });
Run Code Online (Sandbox Code Playgroud)


小智 5

我解决了将商店包装在函数中的问题:

/*** THIS DOES NOT WORK ****/
const router = useRouter();

export const useLoginStore = defineStore("login", {
  state: () => ({
    loading: false,
    error: "",
  }),
  actions: {
    loginAction(credentials: AuthenticationRequest): Promise<void> {
      await login(credentials);
      router.replace("/")
    },
  },
});



/*** This actually works ***/
export default function useLoginStore() {
  const router = useRouter();

  return defineStore("login", {
    state: () => ({
      loading: false,
      error: "",
    }),
    actions: {
      loginAction(credentials: AuthenticationRequest): Promise<void> {
        await login(credentials);
        router.replace("/")
      },
    },
  })();
}
Run Code Online (Sandbox Code Playgroud)

  • 对我有用 (2认同)