@tur1/resources-vue
v1.6.9
Published
This package helps you create filters, actions, resources, and pages efficiently in your Vue project.
Downloads
815
Readme
@tur1/resources-vue Package
This package helps you create filters, actions, resources, and pages efficiently in your Vue project.
Installation
First, install the package:
npm install @tur1/resources-vue
Usage
Adding Commands
Add the following commands to your project's package.json
file under the scripts
section:
"scripts": {
"make:filter": "node ./node_modules/@tur1/resources-vue/scripts/create-filter.js",
"make:action": "node ./node_modules/@tur1/resources-vue/scripts/create-action.js",
"make:resource": "node ./node_modules/@tur1/resources-vue/scripts/create-resource.js",
"make:page": "node ./node_modules/@tur1/resources-vue/scripts/create-page.js"
}
Creating Pages
To create a new page, run the following command:
npm run make:page Users
This will generate a new page structure for Users
. It will also automatically register the Users
routes in router/index.vue
.
Below is the expected file structure generated by the command:
pages
├── Home
├── Users
│ ├── Actions
│ │ └── DeleteAction.js
│ ├── api
│ │ └── useUsersApi.js
│ ├── Filters
│ │ └── Filter.js
│ ├── routes
│ │ └── UsersRoutes.js
│ ├── services
│ │ └── useUsersService.js
│ ├── stores
│ │ └── UsersStore.js
│ ├── views
│ │ ├── create.vue
│ │ ├── edit.vue
│ │ ├── index.vue
│ │ └── show.vue
│ └── UsersResource.js
Resource Class
To render a table, you need to create a resource class and pass it to the ResourceList
component.
import { ResourceList } from '@tur1/resources-vue'
import UsersResource from '@/pages/Users/UsersResource'
<ResourceList :resource="new UsersResource()" />
Fields
Example:
fields() {
return [
Column().make('id').label('ID'),
Column().make('user.avatar')
.image()
.label('Image')
.hidden((record) => record.isAdmin),
Column().make('created_at')
.label('Created At')
.align('center')
.format(date => new Date(date).toLocaleDateString()),
Column().make('gender')
.label('Gender')
.badge((value) => value === 'Female' ? 'primary' : 'secondary'),
Column().make('status')
.label('Status')
.badge({ active: 'success', inactive: 'danger' }),
];
}
Actions
Example:
actions()
{
return [
Action()
.deleteAction()
.make(async (record) => await destroy(record))
.onSuccess((item) => console.log(item))
.onFailure((err,item) => console.log(err,item)),
Action()
.label('show')
.icon('fa-solid fa-pen-to-square')
.class('text-primary')
.route((record) => ({
name: 'users.show',
params: {
id: record.id
}
})),
new EditUser()
]
}
Bulk Actions
You can define bulk actions for your resources using the bulkActions
method. This method allows you to apply an action to multiple records at once.
Example: Defining Bulk Actions
/**
* Get the bulk actions for the resource.
*/
bulkActions() {
return [
Action()
.label('log items')
.class('text-primary')
.make((records) => console.log(records)) // Apply the action to the selected records
];
}
Data
The data()
function retrieves resource data. You can return the data array alone or with pagination details, links, and meta data.
Example without pagination:
async data() {
return [{id:1 ,name: item 1 },{id:2 ,name: item 2 }];
}
Example with pagination:
async data() {
let response = await useUsersApi.getPaginatedList();
return {
data: response.data.data,
links: response.data.links,
meta: response.data.meta,
};
}
Adding Filters
npm run make:filter Users/StatusFilter
You can add filters to your pages using the ResourceFilter
class. If the filter type is select
, you have two ways to get options: either by returning an array or an object with key-value pairs for label and value.
Example Filter Implementation:
import { ResourceFilter } from "@tur1/resources-vue";
class StatusFilter extends ResourceFilter {
/**
* The label of the filter (optional).
* @type {string}
*/
label = "Filter";
/**
* The type of the filter.
* @type {string}
*/
type = "select";
/**
* Handle the filter logic.
*/
handle() {
// Implement the filter logic here when the value is selected
}
/**
* Get the options for the filter if type is 'select'.
* This method can return options in various formats
*/
options() {
// 1. As a simple array:
let optionsArray = ["option 1", "option 2"];
return optionsArray;
// 2. As an object with label and value:
let optionsObject = [
{ id: 1, title: "option 1" },
{ id: 2, title: "option 2" },
];
return {
data: optionsObject,
label: "title",
value: "id",
};
// 3. load options dynamically:
let { loadOptions } = useService()
return {
data: loadOptions,
label: 'title',
value: 'id'
};
}
}
export default Filter;
Adding Actions
You can generate a new action by running the command below.
npm run make:action Users/EditUserAction
This command will generate the EditUserAction.js file in the appropriate folder (for example, inside pages/Users/Actions).
import { ResourceAction } from "@tur1/resources-vue";
class EditUserAction extends ResourceAction {
/**
* The label of the action.
* @type {string}
*/
label = 'Edit';
/**
* The icon of the action.
* @type {string}
*/
icon = 'fa-solid fa-pen-to-square';
/**
* The CSS class for the action button.
* @type {string}
*/
class = 'text-primary';
/**
* Whether the action requires confirmation.
* @type {boolean}
*/
requiresConfirmation = false;
/**
* Whether the action is a delete action.
* @type {boolean}
*/
isDeleteAction = false;
/**
* Returns the route object for the action.
* @param {Object} record
* @returns {{ name: string, param?: string }}
*/
route(record) {
return {
name: 'users.edit',
params: { 'id': record.id }
};
}
/**
* Determines whether the action should be hidden.
* @param {Object} record
* @returns {boolean}
*/
hidden(record) {
return false;
}
/**
* Executes the action.
* @param {Object} record
* @returns {void}
*/
async make(record) {
}
}
Action Function
You can define actions using the Action function. Here's how you can set up delete and show actions:
To apply an action, use the make
method.
To define the action's route, use the route
method.
Example: Delete Action
Action()
.deleteAction()
.make(async (record) => await destroy(record))
.onSuccess((item) => console.log(item)) // Handle success
.onFailure((err, item) => console.log(err, item)); // Handle failure
Action()
.label('show')
.icon('fa-solid fa-pen-to-square')
.class('text-primary')
.route((record) => ({
name: 'admins.show', // Define the route for the action
params: {
id: record.id // Pass the record ID as a parameter
}
}));
class DeleteUser extends ResourceAction {
/**
* The label of the action.
* @type {string}
*/
label = 'Delete';
/**
* The icon of the action.
* @type {string}
*/
icon = 'fa-solid fa-trash-can';
/**
* The CSS class for the action button.
* @type {string}
*/
class = 'text-danger';
/**
* Whether the action requires confirmation.
* @type {boolean}
*/
requiresConfirmation = true;
/**
* Whether the action requires delete.
* @type {boolean}
*/
isDeleteAction = true;
/**
* Executes the action.
* @param {Object} record
* @returns {void}
*/
async make(record) {
await destroy(record)
}
hidden(record)
{
return false;
}
}
Notifications
Example:
import { useResourceNotification } from "@tur1/resources-vue";
useResourceNotification.error("Error message");
useResourceNotification.success("Success message");
Query String Management
to manage query strings for URL parameters.
Example:
import { useResourceQueryString } from "@tur1/resources-vue";
let queryString = useResourceQueryString();
queryString.add("status", "active"); // ?status=active
queryString.remove("status"); // removes the status parameter
queryString.reset(); // removes all query parameters
queryString.get("status"); // returns 'active'
useResourceApi
To make API requests, you can use the useResourceApi
:
import { useResourceApi } from "@tur1/resources-vue";
useResourceApi("http://example.test").get("/users");
Router Setup with setResourceRouter
To use filters based on query strings, you need to integrate the setResourceRouter
function in your Vue Router setup. Modify your router/index.js
:
import { createRouter, createWebHistory } from "vue-router";
import { setResourceRouter } from "@tur1/resources-vue";
const router = createRouter({
history: createWebHistory(import.meta.env.BASE_URL),
routes: [],
});
setResourceRouter(router);