Utilizing @casl/vue in conjunction with pinia: A guide to integrating these

I'm currently facing an issue with integrating @casl/ability and Vue 3 with Pinia. I'm unsure of how to make it work seamlessly.

Here is a snippet from my app.js:

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

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

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

// ...

app.mount('#app')

This is what my ability.js file looks like:

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

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

export default customAbility

An error message keeps popping up while trying to set this up: https://i.sstatic.net/7xYNe.png

I've referred to Pinia's documentation on Using a store outside of a component, but there seems to be something amiss in my implementation. (P.S. The Pinia setup works fine elsewhere in my project; just need guidance on getting it right here.)

Answer №1

Perhaps it would be helpful to establish rules in pinia. In order to utilize the ability there, you must first make it accessible within the store (similar to 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);
});

In store.js, you can now access the ability like this:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How does webpack identify the index.html file as the entry point for loading the bundle.js file?

I've noticed that without specifying a command to load index.html, webpack is automatically loading the page whenever I make changes in a file. Below are the attached files: webpack.config.js and package.json webpack.config.js var config = { entry: ...

How can Selenium in Python be used to click a JavaScript button?

I need help automating the click of a button on a webpage using selenium Here is the HTML for the button: <div class="wdpv_vote_up "> <input value="7787" type="hidden"> <input class="wdpv_blog_id" value="1" type="hidden"> </div& ...

When initializing a new Date object with a number versus a string, the resulting values will vary

As I delve deeper into JavaScript, I stumbled upon an interesting quirk in its behavior. When creating date objects like this: var stack = new Date(1404187200000) // 07-01-2014 var overflow = new Date('07-01-2014') I noticed that when comparin ...

Dynamically setting the height of elements using jQuery with incremental values

My Objective: I am trying to dynamically adjust the height of each li element within a ul.container. The goal is to find the tallest li, add 25px to its height, and then apply that new height to all other li elements in the container. This calculation ne ...

Jquery auto-suggest form validator

I have implemented a search dropdown menu using jQuery. Everything is working fine, and the 'not match' message displays properly when entering data that does not match any items. However, if I select an item from the dropdown and then modify it ...

Encountering problems when transforming Next.js server components into client components

I've been working on a blog site using next.js. Initially, I had a home page that was a server component, but I wanted to convert it into a client component to add interactivity like pagination. However, after converting the code to a client componen ...

Ensure NodeJS/JSDom waits for complete rendering before performing scraping operations

I am currently facing an issue with scraping data from a website that requires login credentials. When I try to do this using JSDom/NodeJS, the results are inconsistent compared to using a web browser like Firefox. Specifically, I am unable to locate the l ...

Learn how to create a half and half color scheme in an HTML table

I have created an HTML table that resembles a calendar. Various events are registered in the calendar, each distinguished by its color. However, I am looking to change the colors of the cells to be half and half. The image I desire is similar to this: C ...

What is the best way to keep track of dynamically inserted input fields?

I've created a form with two text boxes: one for entering people's "name" and another for their "surname." By clicking on the page, you can add additional pairs of text boxes for both "name" and "surname," allowing users to input as many pairs as ...

What is the process of replacing fetch with JavaScript?

Looking to test my React application and mock the backend calls, I made the decision to swap out fetch with a Jest function that returns a static value. The issue I encountered was my inability to override the default fetch behavior. After some research, ...

Create a custom element in React to detect and encapsulate links

I could really use some assistance with this issue. I have a bunch of text blocks containing links and have been utilizing linkifyjs's React component to automatically wrap the links in anchor tags. However, now I am looking to add a custom button nex ...

Turn off escape option when PointerLockControls are in use

Is there a way to prevent the ESCAPE option from being activated (when using PointerLockControls and ThreeJS) by pressing the escape key on the keyboard? I have a different function in mind for this key in my project! Appreciate any assistance in advance ...

The JavaScript code for summing two numbers is not functioning as expected

My HTML code takes a user input number, performs a calculation using a formula, and displays the output. The chosen input is inserted into the formula, and the result is added to the original number. However, there seems to be an issue with adding decimal ...

What is the best way to match the minimum height of one div to the height of another div?

I need to dynamically set the minimum height of #wrapper equal to the height of #sidebar, but the height of #sidebar is not fixed. Here is my attempt at achieving this with JavaScript: var sidebarHeight = jQuery('#sidebar').height; jQuery(&apos ...

Typescript's forEach method allows for iterating through each element in

I am currently handling graphql data that is structured like this: "userRelations": [ { "relatedUser": { "id": 4, "firstName": "Jack", "lastName": "Miller" }, "type": "FRIEND" }, { "relatedUser": ...

Vuex - The action type CreateProfile or ProfileList is not recognized

Hello everyone! I am working on a project where I need to create models and maintain a list of them. Currently, I have integrated two separate projects successfully: https://github.com/apirobot/django-vue-simplenote and https://github.com/jakemcdermott/ ...

Preserving client-side page state during page reloads in angular.js apps

I am currently developing a Single Page application using angular.js and I have encountered an issue that I am struggling to resolve. When performing a full page refresh in an angular app, how can we verify if the user still has a valid session? While Sta ...

How can we sort an array based on the inner HTML values of its children elements in JavaScript?

Can you arrange a JavaScript array based on the innerText values of its HTML elements? I am generating a div element (class="inbox" id="inbox${var}") with a number as its innerText, then adding all these divs to an array (numArr). I wan ...

Tips for transferring a Vuex-stored value to a variable within Vuejs 3 (Quasar 2)

Currently, I have a Vuex store where I am storing a date (referred to as date). In my Vue.js template (using Quasar 2 beta 12), I can easily access this date using {{ date }}. If I make changes to the date in the store, it reflects immediately in the {{ ...

Is there a way to link Dom $(this) from a different function?

Could you please review this code and advise on how I can bind $(this) in an external function within a DOM event? $(".adder").on("click", function(){ updateText(); }); function updateText(){ $(this).next(".mapper").html("Got You!"); } <scrip ...