Search code examples
javascriptvue.jscasl

After build Vue.js project the CASL library not working


I try check ability by class instance:

<Can
 I="delete"
 :a="createHomeTask(item.teacher.id)"
>
</Can>

Where ability description:

if (role === 'ROLE_teacher') {
  can('delete', 'HomeTask', { teacher: user.id });
}

Where createHomeTask:

class HomeTask {
  constructor(teacherId) {
    this.teacher = teacherId;
  }
}

export default function createHomeTask(teacherId) {
  return new HomeTask(teacherId);
}

Before building the project, everything works fine, but after the build, this functionality does not work.

What could be the problem?


Solution

  • I believe this is caused by Vue minifying code when building, so CASL doesn't work properly. This question might be also related to your problem: CASL is not working properly in Vue Production Mode. (However, the link to the docs in the answer is outdated for some reason, but I have this page saved)

    In official docs (at least earlier) solving this problem was covered:

    By default, CASL is looking for modelName attribute on constructor of the passed object (and fallbacks to constructor name if that is blank).

    class Post {
      constructor({ title, published }) {
        this.title = title
        this.published = published
      }
    }
    

    Important: if you use minification for production builds, it will minify class names as well and this example won’t work. For such cases, you can define static modelName attribute on a class.

    In this example, ability will check rules for Post and not for Article:

    class Article {
      static get modelName() {
        return 'Post'
      }
    
      constructor({ title, published }) {
        this.title = title
        this.published = published
      }
    }
    

    I suggest you try doing the following:

    class HomeTask {
      static get modelName() {
        return 'HomeTask'
      }
      constructor(teacherId) {
        this.teacher = teacherId;
      }
    }
    

    I hope this will help you.