Vue JS Sweetalert Confirm refresh module - vue.js

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')
}
})

Related

How to update a table's data in VueJS?

I have a table with date filters (it's a panel with 4 options: day/week/month/year). My task is create pagination. After selection of the filter with specific date range, I fetch data from API and save its response to vuex store. I logged everything - fetching and vuex work fine. But when I start to change filters, my table data isn't updating properly - seems like it uses old stored data when new is added. I tried lots of ways to solve it - using a computed property, special counter, etc. How my problem can be solved? Thanks.
<template>
<div class='page'>
<h1 class='title'>Bookings</h1>
<div class='schedule-page classes bookings' :class='{ isActive: isOpenPopup }'>
<div class='filter-bar-wrapper'>
<div class='row'>
<FilterBar #change='handleFilters' :categories='allCategories' :statuses='bookingClassesStatus' />
<button class='button button--primary button--create' #click='handleCreateBooking'
v-if='caller !== callerOptions.ADMIN'>
Add a new bookings
</button>
</div>
</div>
<div class='table-wrapper'>
<p class='title'>{{ today }}</p>
<table class='bookings-table'>
<thead>
<tr>
<th>ID booking</th>
<th>Date</th>
<th>Time</th>
<th>Studio name</th>
<th>Client name</th>
<th>Class name</th>
<th>Categories</th>
<th>Points</th>
<th>Event creator</th>
<th>Status</th>
<th>Validate code</th>
</tr>
</thead>
<tbody>
<template>
<tr :key='`booking-body-title`' class='empty-row'
v-if='this.newBookingsAmount > 0'>
<td :style='"padding: 12px 16px 12px 28px; color:" + Styles.BLUE'>New bookings</td>
</tr>
<template v-for='(booking, index) in this.bookings'>
// lots of tr/td
</template>
</template>
</tbody>
</table>
<Pagination :pagesNum='this.pages' #change='handlePaging' />
</div>
</div>
</template>
<script>
import { mapGetters, mapActions } from 'vuex'
import moment from 'moment'
import FilterBar from '#/components/schedule/FilterBar'
import STYLES from '#/store/styles'
import bookingStatus from '#/store/modules/bookingStatus'
import Pagination from '#/components/Pagination'
import classStatus from '#/store/modules/classStatus'
import { TAKE_ITEMS_PER_PAGE } from '#/store/modules/admin/config'
import callerOptions from '#/store/modules/admin/bookings/callerOptions'
export default {
props: {
currentStudio: {
type: Object,
},
caller: {
type: String,
required: true,
validator: (value) => {
return Object.values(callerOptions).includes(value)
},
},
},
data() {
return {
bookings: [],
newBookingsAmount: 0,
pages: 0,
callerOptions: callerOptions,
mode: '',
filters: {
startDate: moment()
.startOf('day')
.utcOffset(0, true)
.toISOString(),
endDate: moment()
.endOf('day')
.utcOffset(0, true)
.toISOString(),
},
bookingClassesStatus: bookingStatus,
bookingItem: {
date: null,
class: '',
client: '',
status: '',
numberOfPoints: null,
comment: '',
},
}
},
computed: {
...mapGetters([
'bookingsList',
]),
today() {
switch (this.mode) {
case 'day':
return moment(this.filters.startDate).format('MMMM D')
case 'week':
return `${moment(this.filters.startDate).utc().format('D.MM')} - ${moment(this.filters.endDate).utc().format('D.MM')}`
case 'month':
return moment(this.filters.startDate).format('MMMM, YYYY')
case 'year':
return moment(this.filters.startDate).format('YYYY')
default:
return 'Invalid date'
}
},
},
methods: {
moment,
...mapActions([
'getBookingsList',
'addBooking',
]),
handleFilters(filters, mode) {
this.filters = filters
this.mode = mode
this.refresh()
},
handlePaging(page) {
const rootElement = document.querySelector('.main-content')
if (rootElement) {
rootElement.scrollTo(0, 0)
}
switch (this.caller) {
case callerOptions.ADMIN:
this.getBookingsList({
...this.filters,
page: page,
take: TAKE_ITEMS_PER_PAGE,
})
break
case callerOptions.CLIENT:
this.getBookingsList({
clientId: this.clientInfo.id,
...this.filters,
page: page,
take: TAKE_ITEMS_PER_PAGE,
})
break
case callerOptions.CLASS:
this.getBookingsList({
classId: this.studioClassesInfo.id,
...this.filters,
page: page,
take: TAKE_ITEMS_PER_PAGE,
})
break
case callerOptions.STUDIO:
this.getBookingsList({
studioId: this.studiosItemInfo.id,
...this.filters,
page: page,
take: TAKE_ITEMS_PER_PAGE,
})
break
default:
break
}
this.$router.push({
name: this.$route.name,
query: { page: page, mode: this.mode },
}).catch(() => {
})
this.bookings = [...this.bookingsList.filter(item => this.isNew.includes(item.status)), ...this.bookingsList.filter(item => !this.isNew.includes(item.status))]
this.newBookingsAmount = this.bookingsList.filter(item => this.isNew.includes(item.status)).length > 0 && this.bookingsList !== undefined ? this.bookingsList.filter(item => this.isNew.includes(item.status)).length : 0
this.pages = this.bookingsPages === undefined ? 1 : this.bookingsPages
},
async refresh() {
switch (this.caller) {
case callerOptions.ADMIN:
await this.getBookingsList({
...this.filters,
page: this.$router.currentRoute.query.page,
take: TAKE_ITEMS_PER_PAGE,
})
break
case callerOptions.CLIENT:
await this.getBookingsList({
clientId: this.clientInfo.id,
...this.filters,
page: this.$router.currentRoute.query.page,
take: TAKE_ITEMS_PER_PAGE,
})
break
case callerOptions.CLASS:
await this.getBookingsList({
classId: this.studioClassesInfo.id,
...this.filters,
page: this.$router.currentRoute.query.page,
take: TAKE_ITEMS_PER_PAGE,
})
break
case callerOptions.STUDIO:
await this.getBookingsList({
studioId: this.studiosItemInfo.id,
...this.filters,
page: this.$router.currentRoute.query.page,
take: TAKE_ITEMS_PER_PAGE,
})
break
default:
break
}
await this.$router.push({
name: this.$route.name,
query: { page: 1, mode: this.mode },
}).catch(() => {
})
this.newBookingsAmount = this.bookingsList.filter(item => this.isNew.includes(item.status)).length > 0 && this.bookingsList !== undefined ? this.bookingsList.filter(item => this.isNew.includes(item.status)).length : 0
this.pages = this.bookingsPages === undefined ? 1 : this.bookingsPages
this.bookings = this.$store.state.bookings.bookingsList
},
},
async mounted() {
await this.getClientsList()
await this.getClassesList()
await this.getStudiosList()
this.mode = this.$route.query.mode === undefined ? 'day' : this.$route.query.mode
},
watch: {
filters: {
handler() {
},
deep: true,
},
bookings: {
handler() {
},
deep: true,
}
},
components: {
FilterBar,
Pagination,
},
}
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
I fixed it. My solution was to add undefined validation inside rows

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>

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
})
}
}
)
}

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

get the form values on the same page after submit the the form in vue.js

i have one form that form is open in popup..so i have only 2 fields in that form..after i submit the form i want to display the form values on the same popup(below the form).how can i do that..can any one help me..
here is my vue page:
<el-form :model="ScheduleInterviewForm" :rules="rules" ref="ScheduleInterviewForm" :inline="true">
<el-form-item prop="schedule_datetime">
<el-date-picker
v-model="ScheduleInterviewForm.schedule_datetime"
type="datetime"
size="small"
placeholder="Select Interview date">
</el-date-picker>
</el-form-item>
<el-form-item prop="interview_type_id">
<el-select size="small" v-model="ScheduleInterviewForm.interview_type_id" placeholder="Select Interview Type">
<el-option
v-for="it in interview_types"
:label="it.type"
:value="it.id">
</el-option>
</el-select>
</el-form-item>
<ElButton
type="success"
size="small"
#click="ScheduleInterview('ScheduleInterviewForm', c.hrc_id)">
SCHEDULE INTERVIEW
</ElButton>
</el-form>
<el-alert
v-show="interviewScheduled"
title="INTERVIEW SCHEDULED!"
type="success">
</el-alert>
<el-form :model="ScheduleInterviewForm" :rules="rules" ref="ScheduleInterviewForm" :inline="true">
<el-form-item prop="schedule_datetime">
</el-form-item>
</el-form>
export default {
props: ['c', 'interview_types'],
data() {
return {
ResumeDialog: false,
ScheduleInterviewForm: {
schedule_datetime: null,
interview_type_id: null,
},
rules: {
schedule_datetime: [
{ type: 'date', required: true, message: 'Select Schedule time', trigger: 'blur' },
{ validator: isDateFuture, trigger: 'blur' },
],
interview_type_id: [
{ type: 'number', required: true, message: 'Select Interview type', trigger: 'blur' }
],
},
interviewScheduled: null,
}
},
methods: {
ScheduleInterview(form, hrcId) {
var that = this;
this.$refs[form].validate((valid) => {
if (valid) {
// AJAX: Create HrRequest
axios.post('/ajax/schedule_interview', {
interviewTypeId: this.ScheduleInterviewForm.interview_type_id,
scheduleDatetime: this.ScheduleInterviewForm.schedule_datetime,
hrcId
})
.then(function(res) {
that.interviewScheduled = true;
setTimeout(() => that.interviewScheduled = false, 3000);
console.log(res);
// that.candidates = res.data.candidates;
})
.catch(function(err) {
console.log(err);
});
} else {
return false;
}
});
},
},
components: { ElButton, ElDialog, ElCard },
}
here is my js page:
const app = new Vue({
el: '#app',
data: () => ({
hr_request: window.data.hr_request,
candidates: window.data.candidates,
interview_types: window.data.interview_types,
}),
methods: {
ScheduleInterview(requestCandidateId, interviewTime) {
console.log(requestCandidateId, interviewTime);
},
},
components: {
Candidate,
Schedule,
}
});
Please can any one help me..
Thanks in advance..
Since you want the inputed values in the form show up af
ter the form is successfully submitted
Add a property in your data property as below:
data(){
return{
showFormValues = false;
}
}
Add a div with the inputed values in paragraph tags below the form and show the div only if form is sucessfully sunbmitted usimg v-show as below:
<div v-show="showFormValues">
<p>date: {{ScheduleInterviewForm.schedule_datetime}}</p>
<p>type: {{ScheduleInterviewForm.interview_type_id}}</p>
</div>
Now in the success part then block of your form submittion click method set the value of showFormValues = true like this:
ScheduleInterview(form, hrcId) {
var that = this;
this.$refs[form].validate((valid) => {
if (valid) {
// AJAX: Create HrRequest
axios.post('/ajax/schedule_interview', {
interviewTypeId: this.ScheduleInterviewForm.interview_type_id,
scheduleDatetime: this.ScheduleInterviewForm.schedule_datetime,
hrcId
})
.then(function(res) {
that.interviewScheduled = true;
//show the input form values on succesful form submission
that.showFormValues = true;
setTimeout(() => that.interviewScheduled = false, 3000);
console.log(res);
// that.candidates = res.data.candidates;
})
.catch(function(err) {
console.log(err);
});
} else {
return false;
}
});
},