javascript - 不能在单个商店内使用 vue-router 和 pinia

标签 javascript vue.js vue-router pinia

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

import router from '../router'
路由器可以工作,但 pinia 失败并出现错误
Uncaught ReferenceError: Cannot access 'useAuthStore' before initialization
at axiosroot.ts

@line let authStore = useAuthStore(pinia);
//这里是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"},
  
});
当我从 vue-routen useRouter 导入路由器时未定义
import {useRouter} from 'vue-router'
const router =useRouter();
错误
Uncaught TypeError: Cannot read properties of undefined (reading 'push') 
--- 
error @ line router.push({name:'Login'})
//这里是剩下的相关代码

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'})
   },
 },
});

最佳答案

路由器必须用作 pinia 中的插件。我在 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)
})
这将为您创建的每个商店添加 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)
现在您可以访问商店中的路由器。
export const useMyStore = defineStore("myStore", {
  state: () => {
    return {};
  },
  actions: {
    myAction() {
      this.$router.push({ name: 'Home' }); 
  },
});

关于javascript - 不能在单个商店内使用 vue-router 和 pinia,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70681667/

相关文章:

javascript - 在动态路由组件上时,VueJS 路由导航不起作用

routes - Nuxt.js 中不同子域的不同路由

vue.js - 创建 URL 并根据其参数设置 Vue.js Vuex 状态

javascript - 类型错误 : render is not a function updateContextConsumer

javascript - 如何使用 JavaScript 中的 this.value 从下拉列表中检查特定值

javascript - 有没有更好的方法来执行此代码?也许使用过滤器或减少?

javascript - Vue.js 如何从 Json 属性获取键(左侧值)。

javascript - 当用户点击另一个 DOM 元素时停止 setInterval 计时器

vue.js - 我应该如何处理 Vuex 中的事件?

javascript - Vue 路由器 + Vuex : how to make beforeEach route guard wait for Vuex state change?