gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 00:26:02 41 4
gpt4 key购买 nike

我正在使用 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/

41 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com