如何使用@casl/vue与pinia

k5ifujac  于 2023-10-23  发布在  Vue.js
关注(0)|答案(1)|浏览(184)

我目前在Vue 3中使用@casl/ability,但我不知道如何让它与Pinia一起工作。
下面是我的app.js的样子:

import { createApp } from "vue"
const app = createApp({})

// pinia
import pinia from "./store"
app.use(pinia)

// casl
import { abilitiesPlugin } from "@casl/vue"
import ability from "./cacl/ability"
app.use(abilitiesPlugin, ability, {
    useGlobalProperties: true
})

// ...

app.mount('#app')

下面是我的ability.js的样子:

import { defineAbility } from "@casl/ability"
import { useMainStore } from "../store/main"

const ability = defineAbility((can, cannot) => {
    const store = useMainStore()
    if (store.user.role === "admin") {
        can("read", "Post")
    }
    // ...
})

export default ability

我得到这个错误:

我已经检查了Pinia的文档关于Using a store outside of a component,但我不太确定我在这里做错了什么?(Pidoss. Pinia正在按预期为我的项目的其余部分工作。我只是不知道如何让它在这里工作。

whhtz7ly

whhtz7ly1#

也许你最好用皮尼亚来定义规则。要在那里使用能力,你必须在商店内使用它(类似于vue-router):
main.js:

import { abilitiesPlugin } from "@casl/vue";
import { createMongoAbility } from "@casl/ability";

const ability = createMongoAbility();
app.use(abilitiesPlugin, ability);
pinia.use(({ store }) => {
  store.ability = markRaw(ability);
});

在store.js中,你现在可以像这样访问能力:

actions: {
  initCasl() {
    const builder = new AbilityBuilder(this.ability);
    if (this.user.role === "admin") {
      builder.can("read", "Post")
    }
    this.ability.update(builder.rules);
  }
}

相关问题