Vuetifyjs DataTable fires 2 additional http requests during component initialization - vue.js

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

Related

VUE.JS API data by using axios show in V-data-table didn't work: it didn't show data

I am a beginner and I try to reach API and show the table by using Vue.js and Vuetify.
I got data from API but I can't show it by v-data-table.
This is my code:
HTML part
<v-data-table :items="data" :headers="headers" :items-per-page="5">
<template slot="data" slot-scope="props">
<td>{{ props.data.userId }}</td>
<td>{{ props.data.id }}</td>
<td>{{ props.data.title }}</td>
</template>
</v-data-table>
script part
<script>
import axios from "axios";
export default {
name: "Current",
data: () => ({
items: ["albums", "todos", "posts"],
selected: "",
headers: [
{ text: "USER_ID", align: "start", sortable: false, value: "userId" },
{ text: "ID", value: "id" },
{ text: "TITLE", value: "title" },
],
data:[],
}),
methods: {
getData() {
axios
.get("https://jsonplaceholder.typicode.com/users/1/" + this.selected ,{dataType: 'json'})
.then((response) => { this.data = response.data;})
.catch((err) => alert(err));
},
},
mounted() {
this.getData();
}
};
</script>
Here is the output that I got
Here is what I want
I refactored your code, first of all when you fetch data from json placeholder there is a single object in the response, you have to push that object to data: [], instead of assigning. Also, it looks like your v-data-table template looks weird, and values from headers should match a key name from response data.
<template>
<v-app>
<v-data-table :items="data" :headers="headers" :items-per-page="5">
<template v-slot:items="props">
<td>{{ props.item.id }}</td>
<td>{{ props.item.name }}</td>
<td>{{ props.item.email }}</td>
</template>
</v-data-table>
</v-app>
</template>
<script>
import axios from "axios";
export default {
name: "App",
data: () => ({
items: ["albums", "todos", "posts"],
selected: "",
headers: [
{ text: "USER_ID", align: "start", sortable: false, value: "id" },
{ text: "EMAIL", value: "email" },
{ text: "NAME", value: "name" },
],
data: [],
}),
methods: {
getData() {
return axios
.get("https://jsonplaceholder.typicode.com/users/1/" + this.selected, {
dataType: "json",
})
.then((response) => {
this.data.push(response.data)
})
.catch((err) => alert(err));
},
},
mounted() {
this.getData();
},
};
</script>

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

Search in vuetify datatable (server side)

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>

Load data from API into mdbootstrap datatable (vue.js, axios)

I want to load data from my API into a mdbootstrap datatable.
How can I write a method, that calls the getPosts() API and writes the results into the rows[] array?
<template>
<mdb-datatable
:data="data"
striped
bordered
>
</template>
<script>
import { mdbDatatable } from 'mdbvue'
import api from '#/api'
export default {
name: 'TPanels',
components: {
mdbDatatable },
data: function () {
return {
loading: false,
posts: [],
model: {},
claims: '',
data: {
columns: [{
label: 'ID',
field: 'immo_id',
sort: 'asc'
},
{
label: 'Titel',
field: 'title',
sort: 'asc'
},
{
label: 'Preis',
field: 'price',
sort: 'asc'
}],
rows: [{
immo_id: XXX,
title: YYY,
price: ZZZ,
}],
}
}
},
async created () {
this.refreshPosts()
this.setup()
},
methods: {
async setup () {
this.claims = await this.$auth.getUser()
},
async isAuthenticated () {
this.authenticated = await this.$auth.isAuthenticated()
},
async refreshPosts () {
this.loading = true
this.posts = await api.getPosts()
}
}
</script>
In my template (vue.js) I can access the API for example with:
<tr v-for="post in posts" :key="post.id">
<td>{{ post.immo_id }}</td>
<td>{{ post.title }}</td>
<td>{{ post.url }}</td>
<td>{{ post.user_id }}</td>
</tr>
so I know that the API is working.
How can I do that please?
I managed to solve the problem by writing the method getTableData(). Important is to use push() on the array in order to have vue rendering the html newly.
},
async created () {
this.refreshPosts()
this.setup()
await this.getTableData()
},
},
getTableData () {
return api.getPosts().then(response => {
var index
let temp = response
console.log(temp)
for (index = 0; index < temp.length; ++index) {
this.data.rows.push({
title: temp[index].title,
immo_id: temp[index].immo_id,
price: temp[index].price
})
}
}
)
}

Vue JS Sweetalert Confirm refresh module

Hi guys I'm using sweetalerts to present alerts to my users, in this case, is a confirmation alert and it's working fine, the only thing is after complete I would like to refresh the module, not the whole page.
As right now I'm using this.$router.go(0) but is refreshing the whole page.
Or Update the Array so the table just shows the updated information:
<td class="text-xs-left">{{ records.item.phone }}</td>
<td class="text-xs-left">{{ records.item.date }}</td>
<td class="justify-center layout px-0">
<v-icon small
class="mr-4"
#click="editItem(records.item.email)">
visibility
</v-icon>
</td>
<td>
<v-icon small
v-on:click="showAlert(records.item.id)">
delete
</v-icon>
</td>
</template>
<v-alert slot="no-results" :value="true" color="error" icon="warning">
Your search for "{{ search2 }}" found no results.
</v-alert>
</v-data-table>
Script
<script>
import Vue from 'vue'
import api from '../store/api.js'
export default {
data() {
return {
pagination: {
descending: true,
rowsPerPage: 10
},
pagination2: {
rowsPerPage: 10
},
search: '',
search2: '',
records: [],
records2: [],
total: [],
confirm: false,
headers: [
};
},
created() {
api.GetAllInquiries().then((response) => {
this.records = response.data;
});
api.GetAllApplications().then((response) => {
this.records2 = response.data;
});
api.GetTotalInquiries().then((response) => {
this.total = response.data;
});
},
methods: {
editItem(email) {
this.$router.push({ name: 'Profile', params: { email: email } });
},
showAlert(id) {
ID: id
})
this.$swal.fire(
'Deleted!',
'Your file has been deleted.',
'success')
}
})
}
}
}
</script>
Basically just add the api call to the response portion of your showAlert function. I'm assuming that they are responsible for populating your tables.
showAlert(id) {
// Use sweetalert2
this.$swal.fire({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((result) => {
api.GetAllInquiries().then((response) => {
this.records = response.data;
});
api.GetAllApplications().then((response) => {
this.records2 = response.data;
});
api.GetTotalInquiries().then((response) => {
this.total = response.data;
});
if (result.value) {
this.$http.post('/api/deleteAddddddddpplication/',
{
ID: id
})
this.$swal.fire(
'Deleted!',
'Your file has been deleted.',
'success')
}
})