Search in vuetify datatable (server side) - vue.js

I'm using vuetify datatables with server side in my app.
Pagination and sorting works fine but I have problem with search input - when I write something in input, new requests dont't send to api.
I found solution with pagination.sync in options but when I try it I get an error in the console:
[BREAKING] 'pagination' has been removed, use 'options' instead. For
more information, see the upgrade guide
https://github.com/vuetifyjs/vuetify/releases/tag/v2.0.0#user-content-upgrade-guide
My code is here:
<template>
<v-container fluid>
<v-text-field
v-model="search"
append-icon="mdi-magnify"
></v-text-field>
<v-data-table
:items="usersList"
:headers="headers"
sort-by="name"
:sort-desc="false"
:options.sync="options"
:server-items-length="totalUsers"
:search="search"
:loading="loading"
loading-text="Ładowanie..."
class="elevation-0"
></v-data-table>
</v-container>
</template>
<script>
export default {
data: () => ({
totalUsers: 0,
usersList: [],
search: "",
loading: true,
options: {},
headers: [
{ text: 'Nazwa użytkownika', value: 'name' },
{ text: 'Adres e-mail', value: 'email' },
{ text: 'Opcje', value: 'actions', sortable: false },
]
}),
watch: {
options: {
handler () {
this.getUsers();
},
deep: true
},
},
mounted () {
this.getUsers();
},
methods: {
getUsers() {
this.loading = true;
userService.getAll(this.options).then(data => {
if (data.status == "success") {
this.usersList = data.items;
this.totalUsers = data.total;
} else {
console.log("Nie udało się pobrać użytkowników.");
}
this.loading = false;
});
},
}
};
</script>

Related

Can't get ID to do delete method (VueX,VueJS)

I follow this guy to do my task:"Call an API to delete items"
https://www.youtube.com/watch?v=cjRst4qduzM&t=967s, start at 12:35.
According this guy said, If you wanna implement delete method there are 2 steps: Firstly, you delete items from state by get ID then use filter method to filter the id you selected.(but when you reload page item still available).Secondly, you call an api to server to delete item in server.
I get in stuck in step one, I can't get ID to delete though before I can select ID to choose company.
This is my component
<div>
<v-data-table
v-model="selected"
:search="search"
:headers="headers"
:items="items"
show-select
hide-default-footer
disable-pagination
class="elevation-1"
>
<template v-slot:item.actions="{ item }">
<v-menu offset-y>
<template v-slot:activator="{ on, attrs }">
<v-btn class="ma-2" v-bind="attrs" v-on="on" icon>
<v-icon>mdi-dots-vertical</v-icon>
</v-btn>
</template>
<v-list>
<v-list-item #click="editCompany(item)">
<span>Edit company</span></v-list-item
>
<v-list-item #click="deleteCompany()">
<span style="color: #e12d39"> Delete company</span>
</v-list-item>
</v-list>
</v-menu>
</template>
</v-data-table>
</div>
</template>
<script>
import { mapGetters } from "vuex";
export default {
props: {
items: {
type: Array,
},
search: { type: String },
},
data() {
return {
headers: [
{ text: "Name", align: "start", value: "name" },
{ text: "Phone Number", value: "phoneNumber" },
{ text: "Website", value: "website" },
{ text: "Address", value: "address" },
{ text: "Currency", value: "currency" },
{ text: "Image Name", value: "imageName" },
{ text: "Actions", value: "actions", sortable: false },
],
};
},
computed: {
...mapGetters({ deletedCompany: "companies/deletedCompany" }),
},
methods: {
deleteCompany(delID) {
console.log("dispatch:", delID);
this.$store.dispatch("companies/deleteCompany", delID);
},
},
};
</script>
and this is my store
import NProgress from "nprogress";
export const namespaced = true;
import Vue from "vue";
import Vuex from "vuex";
import { create } from "#/http/companies";
import VueToast from "vue-toast-notification";
import "vue-toast-notification/dist/theme-sugar.css";
import { getCompanies } from "#/http/companies";
// import { deleteCompanies } from "#/http/companies";
Vue.use(Vuex);
Vue.use(VueToast);
export const state = {
companies: [],
selectedCompanyId: "",
};
export const getters = {
allCompanies: (state) => state.companies,
selectedCompanyId: (state) => state.selectedCompanyId,
deletedCompanyId: (state) => state.deletedCompanyId,
selectedCompany: (state) => state.companies.find((c) => c.id === state.selectedCompanyId),
deletedCompany: (state) => state.companies.filter((c) => c.id != state.deletedCompanyId)
};
export const mutations = {
GET_COMPANIES(state, companies) {
state.companies = companies;
},
DELETE_COMPANIES(state, deletedCompanyId) {
console.log("mutations:", deletedCompanyId)
state.deletedCompanyId = deletedCompanyId;
},
SET_SELECTED_COMPANY_ID(state, selectedCompanyId) {
console.log(selectedCompanyId)
state.selectedCompanyId = selectedCompanyId
},
STORE_ID(state, payload) {
state.routeId = payload;
},
};
export const actions = {
storeID({ commit }, payload) {
commit("STORE_ID", payload);
},
getCompanies({ commit }) {
return getCompanies(NProgress.start()).then((response) => {
commit("GET_COMPANIES", response.data);
NProgress.done();
});
},
selectCompany({ commit }, companyId) {
commit("SET_SELECTED_COMPANY_ID", companyId, NProgress.start());
console.log("đây là id", companyId)
NProgress.done();
},
deleteCompany({ commit }, delId) {
console.log("actions:", delId)
return commit("DELETE_COMPANIES", delId);
},
registerCompany({ commit }, companyInfor) {
return create(companyInfor)
.then(() => {
Vue.$toast.open({
message: "Create company successfully!",
type: "success",
duration: 3000,
dismissible: true,
position: "top-right",
});
})
.catch((error) => {
commit("");
Vue.$toast.open({
message: error,
type: "error",
duration: 3000,
dismissible: true,
position: "top-right",
});
});
},
};
https://www.loom.com/share/1eb12a448aca41df8e4c77cdc8931002?focus_title=1&muted=1&from_recorder=1
pass the id via the click event handler <v-list-item #click="deleteCompany(item.id)">:
methods: {
deleteCompany(delID) {
console.log("dispatch:", delID);
this.$store.dispatch("companies/deleteCompany", delID);
// or this.$store.dispatch("companies/deleteCompany", delID);
},
},
you forgot to pass parameter as item_id to function
<v-list-item #click="deleteCompany(item)">
perhaps this will do the trick

datatable vueJS don´t show data

I´m trayin integrate datatable in my component vue. For this i´m using this library:
https://jamesdordoy.github.io/
i´m install in my proyect, i has configured it, created my component and include in my view, but returned me this message:
Invalid prop: type check failed for prop "data". Expected Object, got Array
my component it´s:
<template>
<div>
<div class="row justify-content-center w-100">
<data-table :data="data" :columns="columns" #on-table-props-changed="reloadTable"></data-table>
</div>
</div>
</template>
<script>
export default {
data() {
return {
url: "/admin/vue/getAllUsers",
data: {},
tableProps: {
search: '',
length: 10,
column: 'id',
dir: 'asc'
},
columns: [
{
label: 'ID',
name: 'id',
orderable: true,
},
{
label: 'Name',
name: 'name',
orderable: true,
},
{
label: 'Email',
name: 'email',
orderable: true,
},
]
}
},
created() {
this.cargar(this.url);
},
methods:{
cargar(url = this.url, options = this.tableProps){
axios.get(url, { params: options })
.then((response) => {
this.data = response.data;
})
.catch((error) => console.error(error));
},
reloadTable(tableProps) {
this.cargar(this.url, tableProps);
}
},
}
</script>
i was trayed with response.data[0] the error disappear but my table it´s empty, i don´t know that i´m doing wrong.
In my controller i have this:
return User::all();
i´m working with laravel 8
thanks for help
you should pass props :items = "data" instead of :data = "data"

nuxt.js fetching data to vuetify table

i am facing problem on fetching data inside vuetify table, it's not showing any data in side table.
MY Laravel API
Route::get('/businesslist',
'BusinessController#userlist')->name('businesslist');
Laravel API Controller
public function businesslist() {
$businesslist = Business::paginate(2)->toJson(JSON_PRETTY_PRINT);
return response($businesslist);
}
}
Nuxt Code
<template>
<v-card>
<v-card-title>
Nutrition
<v-spacer></v-spacer>
<v-text-field
v-model="search"
append-icon="mdi-magnify"
label="Search"
single-line
hide-details
></v-text-field>
</v-card-title>
<v-data-table
:headers="headers"
:items="registerlist"
:search="search"
></v-data-table>
</v-card>
</template>
<script>
export default {
data () {
return {
search: '',
headers: [
{ text: 'SL,No', value: '' },
{ text: 'Name', value: 'name' },
{ text: 'Mobile ', value: 'mobile_number' },
{ text: 'Location ', value: 'location' },
{ text: 'Join Date ', value: 'registration_date' },
{ text: 'Renewal Date ', value: 'registration_renewal_date' },
],
registerlist: [
],
}
axios.get('/Businessregisterlist')
.then(res => this.registerlist = res.data.registerlist)
},
}
</script>
Firstly, you have to call API within a Function like this:
<script>
export default {
data() {
return {
list: []
}
},
methods: {
callAPI() {
axios.get('/', then(function(res){
this.list = res.data.registerList;
}))
}
},
mounted(){
this.callAPI(); // if you need that List on load then you can use mounted() otherwise that function will call during event.
}
}
</script>
Here, inside then() I think it's better to use function(). Because if you use function then it will indicate this Object. So, we can easily access all the Object Properties (Like: data(), methods() etc.).

Display Boolean on Vuetify dataTable

I made a data table with vue vuetify and I fetch my data from my api server.
In my table, everything is display except boolean.
Can you help me to see clearer
Table component
<template>
<v-data-table
:headers="headers"
:items="fixture"
:items-per-page="5"
class="elevation-10"
>
</v-data-table>
</template>
<script>
export default {
name: 'my_fixtures',
props: ['fixture'],
data () {
return {
headers: [
{ text: 'name',value: 'name'},
{ text: 'State', value: 'on' },
{ text: 'Group', value: 'group' },
{ text: 'Recipe', value: 'recipe' },
{ text: 'start', value: 'startDate' },
{ text: 'end', value: 'endDate' },
{ text: 'Action', value: 'action' },
],
items: this.fixtures
}
}
}
</script>
In the object that I receive , the key 'on' is a Boolean.
I have all display , but nothing in the 'on' column
and this is what I do with props
<template>
<v-container>
<my_fixtures v-bind:fixture="fixtures"></my_fixtures>
<router-view></router-view>
</v-container>
</template>
<script>
import my_fixtures from "./greenhouse/fixtures";
export default {
name: "my_client",
data: function (){
return {fixtures: []}
},
components: {my_fixtures},
mounted() {
http.get('fixture/client')
.then(result => {
this.fixtures = result;
})
.catch(error => {
console.error(error);
});
}
}
</script>
Process and print data using methods.
try this.
<td class="text-xs-right">{{ computedOn(props.fixture.on) }}</td>
export default {
methods: {
computedOn (value) {
return String(value)
}
}
}
UPDATE
Modifying original data due to vuetify bug
https://github.com/vuetifyjs/vuetify/issues/8554
export default {
mounted() {
http.get('fixture/client')
.then(result => {
this.fixtures = result.map(value => {
value.on = String(value.on)
})
})
.catch(error => {
console.error(error);
});
}
}

Vuetifyjs DataTable fires 2 additional http requests during component initialization

Component's template:
<v-layout>
<v-flex>
<v-data-table :headers="headers" :items="items" :search="search" :pagination.sync="pagination" :total-items="totalItems"
:loading="loading" class="elevation-1" :rows-per-page-items="sizes">
<template slot="items" slot-scope="props">
<td>{{ props.item.itemWebCode }}</td>
<td>{{ props.item.description }}</td>
<td>{{ props.item.sequence }}</td>
</template>
</v-data-table>
</v-flex>
Component's js code:
import itemHttpService from './../../../services/itemsHttpService.js'
export default {
name: 'items',
data: () => ({
items: [],
loading: true,
pagination: {},
totalItems: 0,
sizes: [10, 30, 60],
search: '',
headers: [
{ text: 'ItemWebCode', align: 'left', sortable: false, value: 'itemWebCode' },
{ text: 'Description', align: 'left', value: 'description', sortable: false },
{ text: 'Sequence', align: 'left', value: 'sequence', sortable: false }
],
}),
async mounted() {
await this.getItems();
},
watch: {
pagination: {
async handler() {
await this.getItems();
},
deep: true
}
},
methods: {
async getItems() {
this.loading = true;
var resp = await itemHttpService.getItems(this.pagination.page, this.pagination.rowsPerPage);
this.items = resp.data.items;
this.totalItems = resp.data.totalItems;
this.loading = false;
}
}
}
itemHttpService file:
import HTTP from './httpBase.js';
const service = {
getItems: async (page, size) => HTTP.get('items', {
params:{
page: page,
size: size
}
}),
};
export default service;
httpBase file:
import axios from 'axios';
const http = axios.create({
baseURL: 'http://localhost:53403/api/'
});
export default http;
I must say the data table rendering and working well. But found thing that looks
a bit strange for me and I'm pretty sure I did stupid mistake. When component initialization server receives 2 additional GET requests: http://prntscr.com/juo7yu Does anyone have an idea what I did wrong?
That bug was fixed in v1.1.0-alpha.6