我正在开发一个基于角色的应用程序。我们有 4 种不同的服务,我们必须根据角色显示操作按钮。例如,管理员可以看到所有操作按钮,但财务团队的人员只能看到财务操作按钮。
我正在使用 CASL js 库,但很难理解它是如何工作的。现在我的所有操作按钮都显示出来了。
能力.js
import { AbilityBuilder } from "@casl/ability";
const user = { name: "Admin", role: "finance" };
// const user = { name: "Finance", role: "finance" };
// const user = { name: "Subscriber", role: "sale" };
// const user = { name: "Subscriber", role: "employee" };
function subjectName(item) {
if (user.role === "admin") {
return "Admin";
}
return item;
}
export default AbilityBuilder.define({ subjectName }, can => {
can(["read"], "Admin");
can(["read"], "Finance");
can(["read"], "Sale");
can(["read"], "Employee");
can(["read"], "Stock");
});
反应 app.js
import React from "react";
import { Can } from "@casl/react";
import ability from "./ability";
import "./App.css";
export default () => {
return (
<div>
<h1>User</h1>
<Can I="read" a="Finance" ability={ability}>
<button>Finance</button>
</Can>
<Can I="read" a="Sale" ability={ability}>
<button>Sale</button>
</Can>
<Can I="read" a="Employee" ability={ability}>
<button>employee</button>
</Can>
<Can I="read" a="Stock" ability={ability}>
<button>stock</button>
</Can>
</div>
);
};