如何使用 PrimeVue DataTable 和 Vue 3 Composition API 根据条件显示选择复选框

问题描述 投票:0回答:1

我是 Vue 新手,正在使用 Vue 3 和组合 API 构建应用程序。我正在使用 PrimeVue Datatable 来显示列表,一切都很顺利,但我需要根据条件显示选择复选框。我面临的问题是,当条件满足时,整个列都消失了。

我希望当满足条件时,只有该行复选框消失。我当前的代码如下。

`

    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-body payment-table pt-0">
                    <DataTable @sort="onSort($event)" :value="data" 
                        class="p-datatable-gridlines" :scrollable="true"
                        scrollHeight="700px" :lazy="true" 
                         v-model:selection="selectedAssetCategoryAttribute"
                        dataKey="Id">
                        <template #empty>
                            No record found.
                        </template>
                        <Column selectionMode="multiple" headerStyle="min-width: 60px"      


                                    :template="checkboxTemplate">
                            <!-- <template #body="action">
                                <div>{{action.data.OwnedBy  }}</div>
                                <div class="p-checkbox p-component" v-  

                                if="filters.IsNull(modulePermission) !== null
                                  &&  modulePermission.roleModuleUpdateFlag 
                                   && ((action.data.OwnedBy == 'CompanyOwned' 
                                 && userType != 'usertype01') || 
                                   ((action.data.OwnedBy == 'SuperCompanyOwned' 
                                && userType == 'usertype01') || userType == 'usertype01'))">
                                    <div class="p-hidden-accessible">
                                        <input type="checkbox">
                                    </div>
                                    <div class="p-checkbox-box p-component"> 
                                        <span class="p-checkbox-icon"></span>
                                    </div>
                                </div>   
                            </template> -->
                        </Column>
                        <Column v-for="col of schema" :field="col.COLUMN_NAME" 
                          :header="col.DISPLAY_NAME" :key="col.Id"
                            style="min-width:260px" :sortable="true">
                            <template #body="action">
                                <span v-if="col.COLUMN_NAME == 'Name'">
                                    <a href="Javascript:void(0);" 
                                         @click="navigate(action.data.Id)"
                                       
                                        v-bind:attribute-id="action.data.Id">{{  
                   action.data[col.COLUMN_NAME] }}</a>
                                    <a href="Javascript:void(0);" v-else="" v-bind:attribute-
                          id="action.data.Id">{{
                                        action.data[col.COLUMN_NAME] }}</a>
                                </span>

                                <span v-if="col.COLUMN_NAME == 'IsMandatory'">
                                    <span v-if="action.data[col.COLUMN_NAME] == false" 
                      title="No">No</span>
                                    <span v-if="action.data[col.COLUMN_NAME] == true" 
                 title="Yes">Yes</span>
                                </span>
                                <span v-if="col.COLUMN_NAME == 'IsActive'">
                                    <div class="text-center">
                                        <a 
                                            href="javascript:;" @click="disable(action.data)" 
                              class="text-danger mx-1">

                                            <span class="label label-light color-3"
                                                title="Click to in-active.">Active</span>
                                        </a>
                                        <a 
                                            href="javascript:;" 
                                style="cursor: not-allowed;"class="text-danger mx-1"
                                            @click="disable(action.data)">
                                            <span class="label label-light color-3"
                                                title="Click to in-active.">Active</span>
                                        </a>

                                        <a 
                                            href="javascript:;" @click="enable(action.data)" 
                 class="text-success mx-1">
                                            <span class="label label-light color-5"
                                                title="Click to active.">In-Active</span>
                                        </a>
                                        <a 
                                            href="javascript:;" style="cursor: not-allowed;" 
                        class="text-success mx-1"
                                            @click="enable(action.data)">
                                            <span class="label label-light color-5"
                                                title="Click to active.">In-Active</span>
                                        </a>
                                    </div>
                                </span>
                                <span
                                    v-if="col.COLUMN_NAME != 'ImagePath' 
                                        && col.COLUMN_NAME != 'IsActive' 
                                && col.COLUMN_NAME != 'Name' 
                                          && col.COLUMN_NAME != 'IsMandatory'">
                                    {{ action.data[col.COLUMN_NAME] }}
                                </span>
                            </template>
                        </Column>
                        <Column style="min-width: 60px" :sortable="false" 
                       headerClass="text-center" alignFrozen="right"
                            frozen="true"
                           >
                            <template #body="action">
                                <span class="actions rw_act">
                                    <i class="fa fa-ellipsis-h action_icon"
                v-bind:attribute-id="[action.data.Id]"
                                        aria-hidden="true"></i>
                                    <span 
                 :class="['action-list-box sixelement' + action.data.Id]">

                                        <span class="list-actions fsm-list" id="action-list"  
                style="width:358px;">
                                            <a href="Javascript:void(0);" 
                            @click="navigate(action.data.Id)"
                                                v-if="filters.IsNull(modulePermission) !== null 
                             && modulePermission.roleModuleUpdateFlag 
                     && ((action.data.OwnedBy == 'CompanyOwned' 
                 && userType != 'usertype01') || ((action.data.OwnedBy == 'SuperCompanyOwned'
                   && userType == 'usertype01') || userType == 'usertype01'))"
                          class="text-info px-2 actions-onclick view-list">
                           <i title="Click to edit." class="fa fa-pencil-alt"></i>
                                            </a>
                                            <a href="Javascript:void(0);"
                                                v-if="filters.IsNull(modulePermission) !== null                                   
                      && modulePermission.roleModuleDeleteFlag 
                                  && ((action.data.OwnedBy == 'CompanyOwned' 
                   && userType != 'usertype01') || 
             ((action.data.OwnedBy == 'SuperCompanyOwned' 
            && userType == 'usertype01') || userType == 'usertype01'))"
                                                @click="deleteCategoryAttribute(action.data)"
                                                
                      class="text-danger px-2 actions-onclick view-list">
                                                <i title="Click to delete." 
                    class="fa fa-trash-alt"></i>
                                            </a>
                                            <i class="fa fa-times close close-action" ></i>
                                        </span>
                                    </span>
                                </span>
                            </template>
                        </Column>

                    </DataTable>
                </div>
            </div>
        </div>
    </div>
</div>
</template>
 <script>
    import Loading from 'vue-loading-overlay';
   import { ref, onMounted, getCurrentInstance,computed  } from "vue";
    import { createConfirmDialog } from "vuejs-confirm-dialog";
     import SimpleDialog from "@/views/shared/SimpleDialog.vue";
     import { createToaster } from "@meforma/vue-toaster";
   import * as Yup from 'yup';
   //Services
     import common from '@/views/shared/common/commonuses.js'
    import AssetCategoryService from "@/service/crmservice/assetcategoryservice";
      import addeditassetcategoryattribute from  
       '../assetcategoryattribute/addeditassetcategoryattribute.vue'
     import CommonService from '@/service/crmservice/commonService'

  export default {
name: 'assetAttributelist',
props: {
    assetCategoryId: Yup.string
},
components: {
    Loading,
    addeditassetcategoryattribute
},
setup(props) {
    const addeditassetcategoryattributeref = ref(false);
    const thisApp = getCurrentInstance();
    const filters = thisApp.appContext.config.globalProperties.$filters;
    const paginatorTemplate = filters.PaginatorTemplate(0, 10);
    const toaster = createToaster({ position: 'top-right' });
    const selectedAssetCategoryAttribute = ref([]);
    const deleteObj = ref({});
    const commonuse = ref(common);
    const deleteIds = ref('');
    const isLoading = ref(false);
    const primarykey = ref(null)
    const assetCategoryId = ref(props.assetCategoryId)
    const schema = ref([]);
    const data = ref([]);
    const assetCategoryService = ref(new AssetCategoryService());
    const totalRecords = ref(0);
    const commonService = ref(new CommonService());
    const userId = ref(null);
    const companyId = ref(null);
    const nameSearch = ref(null);
    const searchText = ref(null);
    const pageSize = ref(10);
    const pageNumber = ref(1);
    const pageSizeList = ref([]);
    const sortBy = ref('desc');
    const sortExp = ref('CreatedOn');
    const modulePermission = ref(null);
    const moduleNameCode = ref('6002');
    const submoduleNameCode = ref('6002');
    const customViewId = ref(null);
    const userType = ref(null);

    const GetPageSizeList = () => {
        commonService.value.GetPageSizeList().then(response => {
            if (response.data != null) {
                pageSizeList.value = response.data.map(item => { return parseInt(item.text) });
            }
        }).catch((error) => {
        });
    }
    const checkboxTemplate = computed(() => {
        return (rowData, column) => {
            return `
      <div>
        <input type="checkbox"
               ${isSelected(rowData) ? 'checked' : ''}
               @click.stop="toggleSelection(rowData)">
      </div>
    `;
        };
    });
    const isSelected = (rowData) => {
        debugger
        return selectedAssetCategoryAttribute.value.some((car) => car.id === rowData.id);
    };

    const toggleSelection = (rowData) => {
        if (isSelected(rowData)) {
            selectedAssetCategoryAttribute.value
        = selectedAssetCategoryAttribute.value.filter((car) => car.id !== rowData.id);
        } else {
            selectedAssetCategoryAttribute.value.push(rowData);
        }
    };
    const onRowSelect = (rowData) => {
        if (rowData.data) {
            if (rowData.data.OwnedBy && rowData.data.OwnedBy 
           == "CompanyOwned" && userType.value != "usertype01") {

            } else if (userType.value != "usertype01") {
                selectedAssetCategoryAttribute.value = 
         selectedAssetCategoryAttribute.value.filter(x => x.Id != rowData.data.Id);
            }
        }
        console.log("onRowSelect", selectedAssetCategoryAttribute.value);
        console.log("onRowSelect", rowData.data);
    }
    const showassetcategoryattributeModal = (id) => {
        addeditassetcategoryattributeref.value.show(id);
    }
    const updateFilter = (event) => {
        let keycode = (event.keyCode ? event.keyCode : event.which);
        if (keycode === 13 || keycode === '13') {
            search();
        }
    }
    const search = async () => {
        setSearchFilter();
        getAttributeListing();
    }
    const reset = async () => {
        searchText.value = null;
        nameSearch.value = null;
        pageSize.value = 10;
        pageNumber.value = 1;
        getAttributeListing();
    }
    const setSearchFilter = () => {
        nameSearch.value = "Name Like '%" + searchText.value + "%'";
    }
    const onSort = (event) => {
        sortExp.value = event.sortFiel;
        sortBy.value = event.sortOrder == '-1' ? 'desc' : 'asc';
        getAttributeListing();
    }

    const onPage = (event) => {
        pageNumber.value = event.page == 0 ? 1 : event.page + 1;
        pageSize.value = event.rows;
        getAttributeListing();
    }


    const getUserInfo = () => {
        userId.value = localStorage.getItem("userId");
        companyId.value = localStorage.getItem("companyId");
    }
    const navigate = (id) => {
        primarykey.value = id;
        showassetcategoryattributeModal(id)
    }


    const getAttributeListing = async () => {
        isLoading.value = true;
        await assetCategoryService.value.getAttributeListing(assetCategoryId.value,
                    nameSearch.value, sortExp.value, sortBy.value, pageNumber.value, 
         pageSize.value, userId.value, companyId.value,
            moduleNameCode.value, submoduleNameCode.value, customViewId.value).then(response =>
          {
                let result = JSON.parse(response.data.result);
                result.Schema = result.Schema.filter(x => x.COLUMN_NAME != 'OwnedBy');
                schema.value = result.Schema;
                data.value = result.Data;
                console.log("data.value", data.value);
                if (result.Data.length > 0) {
                    totalRecords.value = result.Data[0].total_records;
                } else {
                    totalRecords.value = 0;
                }
                paginatorTemplate.value = filters.PaginatorTemplate(totalRecords.value, 
         pageSize.value)
                isLoading.value = false;
            });
    }
    const deleteCategoryAttribute = (event) => {
        console.log(event);
        const { reveal, onConfirm } = createConfirmDialog(SimpleDialog, {
            question: `Are you sure you want to delete  "${event.Name}"?`,
            header: `Delete Asset Category`,
            cancel: `Cancel`,
            confirm: `Ok`,
        });
        onConfirm(async () => {
            isLoading.value = true;
            selectedAssetCategoryAttribute.value = [];
            selectedAssetCategoryAttribute.value.push(event);
            deleteObj.value = {
                companyId: companyId.value,
                userId: userId.value,
                primaryKeys: selectedAssetCategoryAttribute.value
            }
            await assetCategoryService.value.deleteCategoryAttribute(deleteObj.value).then(r =>  
        {
                toaster.success(`"${event.Name}" has been deleted successfully`);
                getAttributeListing();
                isLoading.value = false;
            }, error => {
                getAttributeListing();
                //console.warn(error);
                toaster.error('Something went wrong');
                isLoading.value = false;
            });
        });
        reveal(() => {
            console.log("reveal")
        });
    }
    const deleteMultipleAssetCategoryAttribute = () => {
        if (selectedAssetCategoryAttribute.value.length > 0) {
            const { reveal, onConfirm } = createConfirmDialog(SimpleDialog, {
                question: `Are you sure you want to delete?"?`,
                header: `Delete Asset Category Attribute(s)`,
                cancel: `Cancel`,
                confirm: `Ok`,
            });
            onConfirm(async () => {
                isLoading.value = true;
                deleteObj.value = {
                    companyId: companyId.value,
                    userId: userId.value,
                    primaryKeys: selectedAssetCategoryAttribute.value
                }
                //deleteIds.value = selectedAssetCategoryAttribute.value.map(x => 
               x.Id).join(',');
                await assetCategoryService.value.deleteCategoryAttribute(deleteObj.value).
               then(r => {
                    toaster.
                    success(`Asset Category Attribute(s) has been deleted successfully`);
                    getAttributeListing();
                    isLoading.value = false;
                }, error => {
                    getAttributeListing();
                    console.warn(error);
                    toaster.error('Something went wrong');
                    isLoading.value = false;
                });
            });
            reveal(() => {
                console.log("reveal")
            });
        } else {
            toaster.error('Please select at least one asset category before delete');
        }

    }
    const getModulePermissions = () => {
        // modulePermission.value = commonuse.value.getPermission(moduleNameCode.value);
        modulePermission.value = commonuse.value.getPermission('6001');
        userType.value = JSON.parse(localStorage.getItem("userinfo")).data.userType;
    }




    const enable = (data) => {
        const { reveal, onConfirm } = createConfirmDialog(SimpleDialog, {
            question: `Are you sure you want to active Attribute  "${data.Name}"?`,
            header: `Active Company`,
            cancel: `Cancel`,
            confirm: `Ok`,
        });
        onConfirm(() => {
            if (data.IsActive == false) {
                data.IsActive = true;
            } else { data.IsActive = false; }
            isLoading.value = true;
            assetCategoryService.value. 
                 ActiveInactiveAssetCategoryAttribute(data.Id, data.IsActive, 
                userId.value, companyId.value).then(r => {
                toaster.success(`"${data.Name}" has been activated  successfully.`);
                getAttributeListing();
                isLoading.value = false;
            }, error => {
                getAttributeListing();
                toaster.error('Something went wrong');
                isLoading.value = false;
            });
        });
        reveal(() => {
            getAttributeListing();
        });
    }

    const disable = (data) => {
        const { reveal, onConfirm } = createConfirmDialog(SimpleDialog, {
            question: `Are you sure you want to in-active Attribute  "${data.Name}"?`,
            header: `In-Active Company`,
            cancel: `Cancel`,
            confirm: `Ok`,
        });
        onConfirm(() => {
            if (data.IsActive == false) {
                data.IsActive = true;
            } else { data.IsActive = false; }
            isLoading.value = false;
            assetCategoryService.value.ActiveInactiveAssetCategoryAttribute(data.Id, 
              data.IsActive, userId.value, companyId.value).then(r => {
                toaster.success(`"${data.Name}" has been in-activated  successfully.`);
                getAttributeListing();
                isLoading.value = false;
            }, error => {
                getAttributeListing();
                console.warn(error);
                toaster.error('Something went wrong');
                isLoading.value = false;
            }

            );

        });
        reveal(() => {
            getAttributeListing();
            //this.isLoding = false;
        });
    }
    onMounted(() => {
        getUserInfo();
        getModulePermissions();
        GetPageSizeList();
        getAttributeListing();
    });

    return {
        primarykey,
        assetCategoryId,
        addeditassetcategoryattributeref,
        schema,
        data,
        assetCategoryService,
        pageSize,
        pageNumber,
        pageSizeList,
        sortBy,
        sortExp, paginatorTemplate, filters,
        totalRecords, selectedAssetCategoryAttribute, modulePermission, userType,
        searchText, updateFilter, deleteMultipleAssetCategoryAttribute, 
        checkboxTemplate,isSelected,toggleSelection,
        showassetcategoryattributeModal,
        search, reset,
        getAttributeListing, deleteCategoryAttribute, onSort, onPage,
        assetCategoryService, isLoading,
        getAttributeListing, deleteCategoryAttribute, navigate, disable, enable, onRowSelect
      }

     }
   }
 </script>
<style lang="">

</style>`
datatable vuejs3 selection primevue
1个回答
0
投票

我认为在这种情况下,代码比文本更能说明问题。制作了 https://stackblitz.com/edit/3z633b?file=src%2FApp.vue 来解决这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.