Vue 3 Problem with PrimeVue DataTables Checkboxes component

46 views Asked by At

I have problem with selecting certain checkboxes in Vue 3 compositonApi by primeVue components. For example static data works correctly i can select whichever element i want:

<DataTable v-model:selection="selectedItem" :value="itemsFromApi" dataKey="id" tableStyle="min-width: 50rem">
        <Column selectionMode="multiple" headerStyle="width: 3rem"></Column>
        <Column field="Id" header="id"></Column>
        <Column field="Name" header="Nazwa"></Column>
    </DataTable>

<script setup>
import { ref } from 'vue';

const selectedItem = ref();
const items = ref([
    { id: 1, name: 'does it work' },
    { id: 2, name: 'test' },
]);
</script>

But if i want to fetch all data from api (laravel simple Model::all() return response()->json()) by axios no matter which element i choose it always selecting every element, and i have no idea why it happens.

<template>
    <DataTable v-model:selection="selectedItem" :value="itemsFromApi" dataKey="id" tableStyle="min-width: 50rem">
        <Column selectionMode="multiple" headerStyle="width: 3rem"></Column>
        <Column field="Id" header="id"></Column>
        <Column field="Name" header="Nazwa"></Column>
    </DataTable>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

const selectedItem = ref();
const itemsFromApi = ref(); },
]);

const fetchData = async () => {
    try {
    const response = await axios.get('API_URL');
    itemsFromApi.value = response.data;
    } catch (error) {
        console.error('Error: ', error);
    }
}

onMounted(fetchData);

</script>

I have tried to get it from other endpoints always same result i have no idea why.

1

There are 1 answers

1
Jenny On BEST ANSWER

Your selectedItem and itemsFromApi references need proper initialization.

here is updates script, you should try

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';

const selectedItem = ref([]);
const itemsFromApi = ref([]);

const fetchData = async () => {
    try {
        const response = await axios.get('API_URL');
        itemsFromApi.value = response.data.map(item => ({
            id: item.id,
            name: item.name 
        }));
    } catch (error) {
        console.error('Error: ', error);
    }
}

onMounted(fetchData);
</script>