vue.js 从路由文件访问pinia存储

i1icjdpr  于 12个月前  发布在  Vue.js
关注(0)|答案(2)|浏览(165)

我正在使用Vue 3、Vue Router和Pinia构建一个面包屑组件。我在我的路由上使用了一个breadcrumbs Meta密钥,带有labelparent属性。该组件通过使用router.resolve()递归解析父路由来生成一个数组,然后从此数组创建组件标记。我使用pinia存储,我想使用存储在pinia存储中的属性动态生成路由文件的meta.label属性。
如果我像这样在routes文件中导入pinia商店:

// routes file
import { useRentalStore } from "@/stores/rentalStore";

const rentalStore = useRentalStore();

const routes = [
  // extract from routes array
  {
    path: ":equipment",
    name: "rental-show",
    component: ShowRentalView,
    meta: {
      breadcrumbs: {
        label: () => rentalStore.rental.label,
        parent: "rental-index",
      },
    },
  },
];

我得到以下错误:"getActivePinia()" was called but there was no active Pinia. Did you forget to install pinia? const pinia = createPinia()
我尝试从主入口点main.js传递pinia示例

// main.js
const pinia = createPinia()
const app = createApp(App)

app.use(pinia)
app.use(router)
//...
export { pinia }

// routes file
import {pinia} from '@/main.js'

const rentalStore = useRentalStore(pinia);

但这还是不行。我在Vue 2中使用了类似的方法,上面的方法可以在Vuex中使用,但不能在Pinia中使用。上面返回以下错误消息:Cannot access 'pinia' before initialization
你知道怎么从路由文件进入pinia商店吗?pinia文档建议将useStore()的调用放在函数中,这些函数将在pinia安装后始终运行,但当子组件导航处于活动状态时,父路由组件将不会运行。

f45qwnt8

f45qwnt81#

Pinia创建存储函数而不是存储示例,以避免早期示例化。当在组件外使用时,useRentalStore应该在使用存储的地方调用:

...
label: () => useRentalStore().rental.label,
...
iyr7buue

iyr7buue2#

注意:使用最后一节中的方法,而不是实际使用这种方法。它仅用于解释,只有在没有其他/更好的方法时才应使用。
您需要在初始化路由器之前创建pinia对象。否则,有一点循环依赖的主文件导入路由器,它导入主文件.
解决方案是使用一个单独的文件初始化Pinia,并导入。最好的可能是作为stores目录的索引文件。例如,将其用作stores/index.js

import { createPinia } from "pinia";

const pinia = createPinia();

export default pinia;

(This还提供了一个包含的位置应用Pinia插件,如果你使用任何。
然后,在你的路由器文件中,从这里导入Pinia示例,并将其传递给store函数:

import pinia from "@/stores";
import { useRentalStore } from "@/stores/rentalStore";

const rentalStore = useRentalStore(pinia);

// As before...

然后,在主文件中,导入Pinia示例并使用它:

// ...

import pinia from "@/stores";

const app = createApp(App)

app.use(pinia)
app.use(router)

通常,这是一个反模式。
更好的选择是“使用”它使用的商店。
举例来说:

import { useRentalStore } from "@/stores/rentalStore";

const routes = [
  // extract from routes array
  {
    path: ":equipment",
    name: "rental-show",
    component: ShowRentalView,
    meta: {
      breadcrumbs: {
        label: () => useRentalStore().rental.label,
        parent: "rental-index",
      },
    },
  },
];

只要在使用app.use(pinia)安装Pinia示例后调用store函数,Pinia就会自动使用该示例;只有在安装Pinia示例之前调用store函数时才需要传入。
文档中有一个简短的部分:Using a store outside of a component | Pinia

相关问题