VueJS // HTML render after API response - vue.js

I render html with some data received from server. It's almost fine but I see errors to console while I didn't receive data from server yet.
Here is the code:
<div class="wiget__eventDetails">
<p class="wiget__eventName">{{ show[0] == 'undefined' ? '' : show[0].title }}</p>
<div class="wiget__place">
<span class="wiget__venue">{{ building[0] == 'undefined' ? '' : building[0].title }}, </span>
<span class="wiget__venueHall">{{ hall[0] == 'undefined' ? '' : hall[0].title }}</span>
</div>
<div class="wiget__dateOfEvent">
<span class="wiget__time">{{this.getTime(this.event[0].date)}}</span>
<span class="wiget__date">{{this.getDate(this.event[0].date)}}</span>
</div>
</div>
So while show[0] === 'undefined' I receive an error to console (Error in render: "TypeError: Cannot read property 'title' of undefined") but the page renders and the statement above do not help
Here is full code of the template
<template>
<div class="allPlaces" id="allPlaces">
<div class="wiget__row wiget__row--top wiget__row--top--allPlaces" id="topRow">
<div class="wiget__details wiget__details--allPlaces">
<div class="wiget__logo">
<img class="wiget__img wiget__img--logo" width="28" height="30" src="../../img/kassy_logo_img.png" alt="">
<img class="wiget__img wiget__img--logoTXT" width="59" height="28" src="../../img/kassy_logo_text.png" alt="">
</div>
<div class="wiget__eventDetails">
<p class="wiget__eventName">{{ show[0] == 'undefined' ? '' : show[0].title }}</p>
<div class="wiget__place">
<span class="wiget__venue">{{ building[0] == 'undefined' ? '' : building[0].title }}, </span>
<span class="wiget__venueHall">{{ hall[0] == 'undefined' ? '' : hall[0].title }}</span>
</div>
<div class="wiget__dateOfEvent">
<span class="wiget__time">{{this.getTime(this.event[0].date)}}</span>
<span class="wiget__date">{{this.getDate(this.event[0].date)}}</span>
</div>
</div>
</div>
</div>
<div class="allPlaces__wrapper">
<h1 class="allPlaces__title">Оформление заказа</h1>
<p class="allPlaces__description">Для оформления заказа выберите нужное количество мест</p>
<div class="allPlaces__content">
<div class="allPlaces__entrance" v-for="(entrance, index) in places.entrance">
<div class="allPlaces__infoBlock">
<div>
<div class="allPlaces__available">
<span class="allPlaces__label allPlaces__label--places">Доступно мест:</span>
<span class="allPlaces__data">&nbsp{{entrance.vacant_places}}</span>
</div>
<div class="allPlaces__title allPlaces__title--entrance">{{getEntranceName(entrance)}}</div>
</div>
<div class="allPlaces__price">
<span class="allPlaces__label">Цена: </span>
<span class="allPlaces__data">{{entrance.price}}</span>
</div>
</div>
<div class="allPlaces__orderBlock">
<div class="allPlaces__inputBlock">
<input class="allPlaces__input" type="number" name="amount"
v-model="entrance.value" #blur="showLabel($event, index)">
<label class="allPlaces__label allPlaces__label--input"
#click="hideLabel($event, index)">Количество мест
</label>
</div>
<div class="allPlaces__btnBlock">
<button class="allPlaces__btn allPlaces__btn--minus" type="button" name="button"
#click="removeTicket(entrance, index)"></button>
<button class="allPlaces__btn allPlaces__btn--plus" type="button" name="button"
#click="addTicket(entrance, index)">
</button>
</div>
<button class="allPlaces__btn allPlaces__btn--confirm" type="button" name="button"
#click="addEntrancePlaceToCart(entrance, index)">
<img class="allPlaces__img allPlaces__img--cart" src="../../img/cartWhite.png" alt="Корзина">
<span class="allPlaces__text allPlaces__text--cart">В корзину</span>
</button>
</div>
</div>
</div>
</div>
<div class="wiget__row wiget__row--bottom" id="bottomRow">
<div class="wiget__row">
<div class="wiget__amountBlock">
<span class="wiget__tickets">
<span>Билеты:</span>
<span class="wiget__amount wiget__amount--tickets">{{this.ticketsInCart.count}}</span>
<span>шт.</span>
</span>
<div class="wiget__money">
<span class="wiget__money wiget__money--label">Итого:</span>
<p>
<span class="wiget__amount wiget__amount--money">{{this.ticketsInCart.total}}&nbsp</span>
<span class="wiget__amount wiget__amount--money">руб.</span>
</p>
</div>
</div>
<div class="wiget__btnBlock">
<button class="wiget__btn wiget__btn--goToHall" type="button" name="button"
#click="goToHall()">
Выбрать на схеме
</button>
<button class="wiget__btn wiget__btn--confirm" type="button" name="button"
#click="goToCartPage($event)">Оформить заказ</button>
</div>
</div>
<div class="wiget__row wiget__row--service">
<span class="wiget__service">Сервис предоставлен:</span>
Kassy.ru
</div>
</div>
</div>
</template>
<script>
import vueMethods from '../../mixins/methods'
import { mapState } from 'vuex'
export default {
name: 'allPlaces',
mixins: [vueMethods],
data () {
return {
showTitle: ''
}
},
mounted () {
this.$nextTick(function () {
window.addEventListener('resize', this.updateAllPlacesOnResize)
this.setupAllPlaces()
})
},
methods: {
setupAllPlaces () {
let allPlaces = document.getElementById('allPlaces')
let topRow = document.querySelector('.wiget__row--top')
let wrapper = document.querySelector('.allPlaces__wrapper')
let bottomRow = document.querySelector('.wiget__row--bottom')
let allPlacesHeight = allPlaces.clientHeight
let topRowHeight = topRow.clientHeight
let bottomRowHeight = bottomRow.clientHeight
let wrapperHeight = allPlacesHeight - topRowHeight - bottomRowHeight
console.log('topRowHeight ', topRowHeight)
console.log('allPlacesHeight ', allPlacesHeight)
console.log('bottomRowHeight ', bottomRowHeight)
console.log('wrapperHeight ', wrapperHeight)
wrapper.style.minHeight = wrapperHeight + 'px'
},
updateAllPlacesOnResize (event) {
this.setupAllPlaces()
},
getEntranceName (entrance) {
let sectionId = entrance.section_id
let section = this.section
let sectionName = section.filter(function (e) {
return e.id === sectionId
})
return sectionName[0].title
},
updateEntranceTicketsAmount (index, value) {
console.log(index)
console.log(this.$store.state.onload.eventData.places.entrance)
let label = document.getElementsByClassName('allPlaces__label allPlaces__label--input')
let input = document.getElementsByClassName('allPlaces__input')
input[index].focus()
console.log(label)
// label[index].style.display = 'none'
this.$store.state.onload.eventData.places.entrance[index].value = value
},
addTicket (tickets, index) {
let value = tickets.value
if (value === '') {
value = 1
} else if (value <= 100) {
value = parseInt(value) + 1
} else {
value = parseInt(value)
}
console.log('tickets ', tickets)
console.log('index ', index)
this.updateEntranceTicketsAmount(index, value)
},
removeTicket (tickets, index) {
let value = tickets.value
console.log('value ', value)
if (value === '') {
value = 0
} else if (value <= 100 && value > 0) {
value = parseInt(value) - 1
} else {
value = parseInt(value)
}
this.updateEntranceTicketsAmount(index, value)
},
addEntrancePlaceToCart (entrance) {
console.log('entrance.id to add to cart ', entrance.id)
let db = this.db
let places = parseInt(entrance.value)
console.log('places ', places)
let sessionId = this.sessionId
let entranceId = parseInt(entrance.id)
let params = {db, places, sessionId, entranceId}
this.$store.dispatch('addEntrancePlaceToCart', params) // Добавили место в корзину
},
goToHall () {
this.$store.dispatch('closeAllPlaces')
this.$store.dispatch('openHallPlan')
},
hideLabel (e, index) {
console.log('CLICKED')
console.log('index click', index)
let input = document.getElementsByClassName('allPlaces__input')
input[index].focus()
},
showLabel (e, index) {
console.log(e)
let target = e.target
console.log('BLUR')
console.log('target', target)
let label = document.getElementsByClassName('allPlaces__label allPlaces__label--input')
console.log('target.value ', target.value)
if (target.value === '' || target.value === undefined) {
label[index].style.display = 'block'
} else {
label[index].style.display = 'none'
}
}
},
destroyed () {
window.removeEventListener('resize', this.setupAllPlaces)
},
computed: {
...mapState({
db: state => state.onload.currentDb,
currentEvent: state => state.onload.currentEvent,
modals: state => state.modals,
metric: state => state.onload.eventData.metric,
section: state => state.onload.eventData.section,
show: state => state.onload.eventData.show,
event: state => state.onload.eventData.event,
building: state => state.onload.eventData.building,
hall: state => state.onload.eventData.hall,
places: state => state.onload.eventData.places,
placesSeated: state => state.onload.eventData.places.place,
sessionId: state => state.cart.sessionId,
ticketsInCart: state => state.cart.ticketsInCart
})
}
}
</script>
<style scoped lang="stylus">
#import '../../styles/Root/allPlaces'
#import '../../styles/Root/wiget'
</style>

Related

My page reloads, and the added task wont register

I am creating a to do list for my exam. For some reason the page keep reload when I click add task, and the tasks wont register. I am new to Vue.js and Javascript.
I have problems with finding the issue. It is a simple code, not to complex, but the add task part is not working.
Here is my code:
<template >
<section class="todolist">
<h1 class="title">{{ title }}</h1>
<form class="container">
<h3 class="container__title">New Task </h3>
<input class="container__input" type="text" placeholder="Enter task" v-model="task">
<button class="container__button" #click="addPlanningTask">Add Task</button>
<h3 class="container__title-second">To Do List</h3>
<ul>
<li v-for="(task, index) in tasks" :key="index">
<span>{{ task.name }} </span>
<button class="todolist__button" #click="deletePlanningTask">Remove</button>
</li>
</ul>
<h4 class="container__list-title" v-if="task.length === 0">
List is empty!</h4>
</form>
</section>
<div class="guestlist">
<h4 class="guestlist__title">{{ invited }}</h4>
<span>{{ guestList }}</span>
<button class="guestlist__button" #click="toggleGuestList">Guestlist</button>
<div v-if="isGuestListVisible === true">
<ul>
<li v-for="guest in people" :key="guest.id.value">
{{ guest.name.first }} {{ guest.name.last }}</li>
</ul>
</div>
</div>
</template>
export default {
props: {
titleName: {
type: String,
default: 'todolist',
},
},
data() {
return {
title: 'Planning the party!',
task: '',
tasks: [{
name: ''
}],
invited: 'Who is invited?',
guestList: '',
people: [],
name: '',
isGuestListVisible: false
}
},
created() {
this.addGuest();
},
methods: {
async addGuest() {
const url = 'https://randomuser.me/api/?page=2&results=8';
const res = await fetch(url);
const { results } = await res.json();
this.people = results;
},
toggleGuestList() {
this.isGuestListVisible = !this.isGuestListVisible;
},
addPlanningTask() {
if(this.task.length === 0)
return;
this.tasks.push({
name: this.task
});
},
deletePlanningTask(index) {
this.tasks.splice(index, 1);
},
},
};
</script>
You can use #submit.prevent on form if you don't want to reload page:
new Vue({
el: "#demo",
props: {
titleName: {
type: String,
default: 'todolist',
},
},
data() {
return {
title: 'Planning the party!',
task: '',
tasks: [],
invited: 'Who is invited?',
guestList: '',
people: [],
name: '',
isGuestListVisible: false
}
},
created() {
this.addGuest();
},
methods: {
async addGuest() {
const url = 'https://randomuser.me/api/?page=2&results=8';
const res = await fetch(url);
const { results } = await res.json();
this.people = results;
},
toggleGuestList() {
this.isGuestListVisible = !this.isGuestListVisible;
},
addPlanningTask() {
if (this.task.length === 0) return;
this.tasks.push({ name: this.task });
},
deletePlanningTask(index) {
this.tasks.splice(index, 1);
},
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo" >
<section class="todolist">
<h1 class="title">{{ title }}</h1>
<form class="container" #submit.prevent>
<h3 class="container__title">New Task </h3>
<input class="container__input" type="text" placeholder="Enter task" v-model="task">
<button class="container__button" #click="addPlanningTask">Add Task</button>
<h3 class="container__title-second">To Do List</h3>
<ul>
<li v-for="(task, index) in tasks" :key="index">
<span>{{ task.name }} </span>
<button class="todolist__button" #click="deletePlanningTask">Remove</button>
</li>
</ul>
<h4 class="container__list-title" v-if="task.length === 0">List is empty!</h4>
</form>
</section>
<div class="guestlist">
<h4 class="guestlist__title">{{ invited }}</h4>
<span>{{ guestList }}</span>
<button class="guestlist__button" #click="toggleGuestList">Guestlist</button>
<div v-if="isGuestListVisible === true">
<ul>
<li v-for="guest in people" :key="guest.id.value">
{{ guest.name.first }} {{ guest.name.last }}</li>
</ul>
</div>
</div>
</div>

VueJs | How to combine a In and out animation with library Animate.css?

I'm starting with VueJs.
I would like to combine animation in and out in a modal.
I think I should do a function but can't find how to.
Here my code:
<template>
<div class="backgroundImage" :style="{'background-image': 'url(' + require('../../assets/bkg.jpg') + ')'}">
<div v-if="showModal" #click="showModal = false"></div>
<div class="modal" v-if="showModal">
<div class="animate__animated animate__bounceIn animate__slow">
<img id="synthesisFt" src="../../assets/popup-ftt.jpg" alt="Logo FunkTheTown" title="FunkTheTown" #click="showModal = false"/>
</div>
</div>
<div>
<img class="logo-img" src="../../assets/logo.png" alt="Logo FunkTheTown" title="FunkTheTown" />
</div>
</div>
</template>
<script>
export default {
data () {
return {
showModal: false
}
},
mounted:function(){
this.popup()
},
methods: {
popup : function () {
setTimeout(() => {
this.showModal = true;
}, 3000);
},
// classChange : function () {
// showmodal = false;
// }
}
}
for the off I would like to use animate__animated animate__bounceOut when I click on the modal.
I've resolved the issue, here the code :
<template>
<div class="backgroundImage" :style="{'background-image': 'url(' + require('../../assets/bkg.jpg') + ')'}">
<div v-if="showModal" #click="showModal = false"></div>
<div class="modal" v-if="showModal">
<div class="animate__animated animate__bounceIn animate__slow">
<img id="synthesisFt" src="../../assets/popup-ftt.jpg" alt="Logo FunkTheTown" title="FunkTheTown" #click="anim2()"/>
</div>
</div>
<div class="animate__animated animate__backInDown animate__slow" v-if="showModalLogin">
<div class="modalLogin">
<label>Login</label>
<input class="loginInput" type="text" placeholder="email...">
<label>Password</label>
<input class="loginPassword" type="password" placeholder="password...">
<button class="connexion">Connexion</button>
<button class="join">Join</button>
</div>
</div>
<div>
<img class="logo-img" src="../../assets/logo.png" alt="Logo FunkTheTown" title="FunkTheTown" />
</div>
<div class="animate__animated animate__rotateIn" v-if="showModalLogo" >
<img class="full_logo" src="../../assets/F2T_logo_color.png" >
</div>
<div class="animate__animated animate__rotateIn" v-if="showModalLogo">
<img class="full_logo_right" src="../../assets/F2T_logo_coloreverse.png" >
</div>
</div>
</template>
<script>
export default {
data () {
return {
showModal: false,
showModalLogin: false,
showModalLogo:false,
}
},
mounted:function(){
this.popup()
},
methods: {
popup : function () {
setTimeout(() => {
this.showModal = true;
}, 3000);
},
anim2 : function () {
this.showModal= false;
this.showModalLogin= true;
this.showModalLogo =true;
const element = document.querySelector('.logo-img');
element.classList.add('animate__animated','animate__bounceOut');
}
// classChange : function () {
// showmodal = false;
// }
}
}

VUEX Filtered computed property does not update at state change

I am using vuex , and with getters Iam filtering a array of data in the store.
In a parent component I am fetching the array and send it to a child with props.
The child component resieve filtered array with getters and save it in computed property.
But when I make changes by calling actions, store is updated but filtered array stayed the same.
When I send to the child component original unfiltered array it's okey.
It the vue dev tool I see correct updated getters.
Some of the code is below.
STORE
const getDefaultState = () => {
return {
activities: [],
error: null,
isActivitiesLoading: false,
isActivityUpdating: false,
}
}
const mutations = {
[FETCHING_ACTIVITIES](state) {
state.isActivitiesLoading = true;
state.error = null;
},
[FETCHING_ACTIVITIES_SUCCESS](state, activities) {
state.error = null;
state.isActivitiesLoading = false;
state.activities = activities
},
[FETCHING_ACTIVITIES_ERROR](state, error) {
state.error = error;
state.isActivitiesLoading = false
},
[UPDATING_ACTIVITY](state) {
state.isActivityUpdating = true;
state.error = null;
},
[UPDATING_ACTIVITY_SUCCESS](state, activity) {
state.error = null;
state.isActivityUpdating = false;
const index = state.activities.findIndex(a => a.id === activity.id)
state.activities[index] = activity;
},
[UPDATING_ACTIVITY_ERROR](state, error) {
state.error = error;
state.isActivityUpdating = false
},
}
const actions = {
async fetchActivities({ commit }) {
commit(FETCHING_ACTIVITIES);
try {
const response = await ActivitiesApi.fetchActivities();
const activities = response.data.data;
commit(FETCHING_ACTIVITIES_SUCCESS, activities);
return response.data.data;
} catch (error) {
commit(FETCHING_ACTIVITIES_ERROR, error);
return null;
}
},
async updateActivity({ commit }, payload) {
commit(UPDATING_ACTIVITY);
try {
const response = await ActivitiesApi.updateActivity(payload);
const activity = response.data.data;
commit(UPDATING_ACTIVITY_SUCCESS, activity);
return response.data.data;
} catch (error) {
commit(UPDATING_ACTIVITY_ERROR, error);
return null;
}
},
};
const getters = {
getActivities(state) {
return state.activities;
},
getRunningActivities(state) {
let today = new Date();
const activities = state.activities;
const filteredActivities = activities.filter(function(activity) {
let activityDate = new Date(activity.start_date)
return activityDate <= today
});
return filteredActivities;
},
};
export default {
namespaced: true,
state: getDefaultState(),
getters,
actions,
mutations,
}
PARENT COMPONENT
<template>
<div class="container">
<h3>Running Activities</h3>
<ActivitiesComponent
:initialActivitiesFromStore="runningActivities"
/>
</div>
</template>
import ActivitiesComponent from "../components/Activities";
export default {
components: {
ActivitiesComponent
},
mounted() {
this.$store.dispatch('activities/fetchActivities').then(
() => {
if (this.hasError) {
console.log(this.error)
} else {
}
}
);
},
computed: {
activitiesFromStore() {
return this.$store.getters['activities/getActivities'];
},
runningActivities() {
return this.$store.getters['activities/getRunningActivities']
},
},
}
</script>
CHILD COMPONENT
<template>
<div class="container">
<div v-if="isActivitiesLoading" class="spinner-border spinner"></div>
<div class="row">
<div class="col">
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Activities</th>
<th scope="col">Period</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
<tr v-for="(activity, activityId) in $v.activities.$each.$iter" :key="activityId">
<th scope="row">{{ parseInt(activityId) + 1 }}</th>
<td>
<input type="text" class="form-control" v-model="activity.name.$model">
<div class="alert alert-danger" v-if="!activity.name.required">Print Name</div>
<div v-if="activitiesFromStore[activityId].is_paused" class="alert alert-warning">
Activity is paused
</div>
</td>
<td>
<input type="text" class="form-control" v-model="activity.activity_period.$model">
<div class="alert alert-danger" v-if="!activity.activity_period.required">Print period</div>
<div class="alert alert-danger" v-if="!activity.activity_period.integer || !activity.activity_period.minValue">Period > 0</div>
</td>
<td class="d-flex border-0">
<button #click="activity.$model.is_paused = ! activity.$model.is_paused" class="btn btn-light mr-1" v-bind:class="{ active: !activity.$model.is_paused }">
<span v-if="activity.$model.is_paused">Убрать с паузы</span>
<span v-else>Make pause</span>
</button>
<button #click="updateActivity(activity.$model)" :disabled="
isActivityUpdating || !activitiesChanged(activityId) || !activity.name.required || !activity.activity_period.required || !activity.activity_period.integer || !activity.activity_period.minValue
" type="button" class="btn btn-success mr-1">
<span v-if="isActivityUpdating && activityActed.id == activity.$model.id" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
Change
</button>
<button #click="deleteActivity(activity.$model)" type="button" class="btn btn-danger">
<span v-if="isActivityDeleting && activityActed.id == activity.$model.id" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
Delete
</button>
</td>
</tr>
</tbody>
</table>
<div class="collapse" id="collapseExample">
<div class="form-group row">
<div class="col-4">
<label for="newPassword-input">Name</label>
<input v-model="activityToAdd.name" class="form-control">
<div v-if="$v.activityToAdd.period.$dirty && !$v.activityToAdd.name.required" class="alert alert-danger">Print name</div>
</div>
<div class="col-4">
<label for="newPassword-input">Period</label>
<input v-model="activityToAdd.period" class="form-control">
<div class="alert alert-danger" v-if="$v.activityToAdd.period.$dirty && !$v.activityToAdd.period.required">Print period</div>
<div class="alert alert-danger" v-if="(!$v.activityToAdd.period.integer || !$v.activityToAdd.period.minValue)">period > 0</div>
</div>
</div>
<button #click="addActivity" :disabled="!$v.activityToAdd.name.required || !$v.activityToAdd.period.required || !$v.activityToAdd.period.integer || !$v.activityToAdd.period.minValue" type="button" class="btn btn-primary">
<span v-if="isActivityAdding" class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
add
</button>
</div>
</div>
</div>
</div>
</template>
<script>
import {required, minValue, integer} from "vuelidate/lib/validators"
export default {
props: ['initialActivitiesFromStore'],
data() {
return {
activityActed: null,
justEdited: false,
justAdded: false,
justDeleted: false,
activityToAdd:{
name: '',
period: '',
isPaused: ''
}
}
},
computed: {
activitiesFromStore() {
return this.initialActivitiesFromStore
},
activities() {
return JSON.parse(JSON.stringify(this.initialActivitiesFromStore));
},
},
methods: {
activitiesChanged(id) {
if(this.activitiesFromStore[id] && this.activities[id].name == this.activitiesFromStore[id].name && this.activities[id].activity_period == this.activitiesFromStore[id].activity_period && this.activities[id].is_paused == this.activitiesFromStore[id].is_paused)
return false;
else
return true
},
updateActivity(activity){
this.activityActed = activity;
this.$store.dispatch('activities/updateActivity', activity).then(
() => {
if (this.hasError) {
console.log(this.error)
} else {
this.justEdited = true;
// still the same
console.log(this.$store.getters['activities/getRunningActivities']);
}
}
);
},
},
validations: {
activities: {
$each: {
name: {
required,
},
activity_period: {
required,
integer,
minValue: minValue(0)
},
is_paused: {
required,
},
}
},
}
}
</script>
The problem was that I did not follow the vue specification about modification of an array. I used vm.items[indexOfItem] = newValue which is not reactive.

VueJs // V-for with v-modal // Data update issue after button clicked

UPDATED!!! Full component's code added:
I've inputs rendered via v-for loop. List of inputs depends on an API response. I need a "plus" and "minus" buttons to change input's value. I almost find a solution but value changes only on sibling input change but not on button click.
Here is my code...
<template>
<div class="allPlaces" id="allPlaces">
<div class="wiget__row wiget__row--top" id="topRow">
<div class="wiget__details wiget__details--allPlaces">
<div class="wiget__logo">
<img class="wiget__img wiget__img--logo" width="28" height="30" src="../../img/kassy_logo_img.png" alt="">
<img class="wiget__img wiget__img--logoTXT" width="59" height="28" src="../../img/kassy_logo_text.png" alt="">
</div>
<div class="wiget__eventDetails">
<p class="wiget__eventName">{{this.show[0].title}}</p>
<div class="wiget__place">
<span class="wiget__venue">{{this.building[0].title}}, </span>
<span class="wiget__venueHall">{{this.hall[0].title}}</span>
</div>
<div class="wiget__dateOfEvent">
<span class="wiget__time">{{this.getTime(this.event[0].date)}}</span>
<span class="wiget__date">{{this.getDate(this.event[0].date)}}</span>
</div>
</div>
</div>
</div>
<div class="allPlaces__wrapper">
<h1 class="allPlaces__title">Оформление заказа</h1>
<p class="allPlaces__description">Для оформления заказа выберите нужное количество мест</p>
<div class="allPlaces__content">
<div class="allPlaces__entrance" v-for="(entrance, index) in places.entrance" :key="entrance.id">
<div class="allPlaces__infoBlock">
<div>
<div class="allPlaces__available">
<span class="allPlaces__label allPlaces__label--places">Доступно мест:</span>
<span class="allPlaces__data">&nbsp{{entrance.vacant_places}}</span>
</div>
<div class="allPlaces__title allPlaces__title--entrance">{{getEntranceName(entrance)}}</div>
</div>
<div class="allPlaces__price">
<span class="allPlaces__label">Цена: </span>
<span class="allPlaces__data">{{entrance.price}}</span>
</div>
</div>
<div class="allPlaces__orderBlock">
<div class="allPlaces__inputBlock">
<input class="allPlaces__input" type="number" name="amount" v-bind:id="tickets"
v-model="tickets[index]" #blur="showLabel($event, index)">
<label class="allPlaces__label allPlaces__label--input"
#click="hideLabel($event, index)">Количество мест
</label>
</div>
<div class="allPlaces__btnBlock">
<button class="allPlaces__btn allPlaces__btn--minus" type="button" name="button"
#click="removeTicket(index)"></button>
<button class="allPlaces__btn allPlaces__btn--plus" type="button" name="button"
#click="addTicket(index)">
</button>
</div>
<button class="allPlaces__btn allPlaces__btn--confirm" type="button" name="button"
#click="addEntrancePlaceToCart(entrance, index)">
<img class="allPlaces__img allPlaces__img--cart" src="../../img/cartWhite.png" alt="Корзина">
<span class="allPlaces__text allPlaces__text--cart">В корзину</span>
</button>
</div>
</div>
</div>
</div>
<div class="wiget__row wiget__row--bottom" id="bottomRow">
<div class="wiget__row">
<div class="wiget__amountBlock">
<span class="wiget__tickets">
<span>Билеты:</span>
<span class="wiget__amount wiget__amount--tickets">{{this.ticketsInCart.count}}</span>
<span>шт.</span>
</span>
<div class="wiget__money">
<span class="wiget__money wiget__money--label">Итого:</span>
<p>
<span class="wiget__amount wiget__amount--money">{{this.ticketsInCart.total}}&nbsp</span>
<span class="wiget__amount wiget__amount--money">руб.</span>
</p>
</div>
</div>
<div class="wiget__btnBlock">
<button class="wiget__btn wiget__btn--goToHall" type="button" name="button"
#click="goToHall()">
Выбрать на схеме
</button>
<button class="wiget__btn wiget__btn--confirm" type="button" name="button"
#click="goToCartPage($event)">Оформить заказ</button>
</div>
</div>
<div class="wiget__row wiget__row--service">
<span class="wiget__service">Сервис предоставлен:</span>
Kassy.ru
</div>
</div>
</div>
</template>
<script>
import vueMethods from '../../mixins/methods'
import { mapState } from 'vuex'
export default {
name: 'allPlaces',
mixins: [vueMethods],
data () {
return {
tickets: []
}
},
mounted () {
this.$nextTick(function () {
window.addEventListener('resize', this.updateAllPlacesOnResize)
this.setupAllPlaces()
})
},
methods: {
setupAllPlaces () {
let allPlaces = document.getElementById('allPlaces')
let topRow = document.querySelector('.wiget__row--top')
let wrapper = document.querySelector('.allPlaces__wrapper')
let bottomRow = document.querySelector('.wiget__row--bottom')
let allPlacesHeight = allPlaces.clientHeight
let topRowHeight = topRow.clientHeight
let bottomRowHeight = bottomRow.clientHeight
let wrapperHeight = allPlacesHeight - topRowHeight - bottomRowHeight
console.log('topRowHeight ', topRowHeight)
console.log('allPlacesHeight ', allPlacesHeight)
console.log('bottomRowHeight ', bottomRowHeight)
console.log('wrapperHeight ', wrapperHeight)
wrapper.style.minHeight = wrapperHeight + 'px'
},
updateAllPlacesOnResize (event) {
this.setupAllPlaces()
},
getEntranceName (entrance) {
let sectionId = entrance.section_id
let section = this.section
let sectionName = section.filter(function (e) {
return e.id === sectionId
})
return sectionName[0].title
},
addTicket (index) {
console.log(this.tickets)
console.log(this.tickets[index])
this.tickets[index] = parseInt(this.tickets[index]) + 1
return this.tickets
},
removeTicket (index) {
this.tickets[index] = parseInt(this.tickets[index]) - 1
},
addEntrancePlaceToCart (entrance, index) {
console.log('entrance.id to add to cart ', entrance.id)
let db = this.db
let places = parseInt(this.tickets[index])
console.log('places ', places)
console.log('index ', index)
let sessionId = this.sessionId
let entranceId = parseInt(entrance.id)
let params = {db, places, sessionId, entranceId}
this.$store.dispatch('addEntrancePlaceToCart', params) // Добавили место в корзину
},
goToHall () {
this.$store.dispatch('closeAllPlaces')
this.$store.dispatch('openHallPlan')
},
hideLabel (e, index) {
console.log('CLICKED')
console.log('index click', index)
let input = document.getElementsByClassName('allPlaces__input')
let target = e.target
input[index].focus()
console.log('this.tickets ', this.tickets)
console.log(target)
if (this.tickets === '') {
target.style.display = 'block'
} else {
target.style.display = 'none'
}
},
showLabel (e, index) {
console.log('BLUR')
console.log('index blur', index)
let label = document.getElementsByClassName('allPlaces__label allPlaces__label--input')
console.log(this.tickets[index])
if (this.tickets[index] === '' || this.tickets[index] === undefined) {
label[index].style.display = 'block'
} else {
label[index].style.display = 'none'
}
}
},
destroyed () {
window.removeEventListener('resize', this.setupAllPlaces)
},
computed: {
...mapState({
db: state => state.onload.currentDb,
currentEvent: state => state.onload.currentEvent,
modals: state => state.modals,
metric: state => state.onload.eventData.metric,
section: state => state.onload.eventData.section,
show: state => state.onload.eventData.show,
event: state => state.onload.eventData.event,
building: state => state.onload.eventData.building,
hall: state => state.onload.eventData.hall,
places: state => state.onload.eventData.places,
placesSeated: state => state.onload.eventData.places.place,
sessionId: state => state.cart.sessionId,
ticketsInCart: state => state.cart.ticketsInCart
})
}
}
</script>
<style scoped lang="stylus">
#import '../../styles/Root/allPlaces'
#import '../../styles/Root/wiget'
</style>
Please advise
You tickets is not correctly initialized. The data populated a empty array but the template will add new element without using the VueJs way of adding reactivity.
What happen is similare to:
let tickets = [];
tickets[0] = ...;
In VueJs you should use push to insert an element to an array and not using the "sparse implementation".
So when your places is being populated inside your store you should create the tickets table from the size of it. Something similare to the following in a watcher or elsewhere depending on your need:
this.tickets = this.place.map(_ => 0);

Pagination. How to make moving between pages by clicking on numerals

Tell me how to make it so that when you click on a button from a cycle with page numbers, this particular page opens. Switching along the arrows works for me, but I cannot understand how to switch between pages. I take data from Api. Total posts 98. It is possible to add your posts. On one page only 10 posts are shown.
My html:
<div id="app">
<div class="smallfon">
<div class="blocktwitter"><img src="src/assets/twitter.png" class="twitter"/></div>
<div class="addTextPost">Add a post</div>
<input type="text" v-model="createTitle" class="created"/>
<input type="text" v-model="createBody" class="created"/>
<div><button #click="addPost()" class="addPost">AddPost</button></div>
<div class="post1">
<div class="yourPosts">Your Posts</div>
<ul>
<li v-for="(post, index) of paginatedData" class="post">
<p><span class="boldText">Title:</span> {{ post.title }}</p>
<p><span class="boldText">Content:</span> {{ post.body }}</p>
<button #click="deleteData(index, post.id)" class="buttonDelete">Delete</button>
<button #click="visiblePostID = post.id" class="buttonChange">Change</button>
<div v-if="visiblePostID === post.id" class="modalWindow">
<div><input v-model="post.title" class="changePost"><input v-model="post.body" class="changePost"></div>
<button type="button" #click="changePost(post.id, post.title, post.body)" class="apply">To apply</button>
</div>
</li>
</ul>
<button type="button" #click="page -=1" v-if="page > 0" class="prev"><<</button>
<button class="item"
v-for="n in evenPosts"
:key="n.id"
v-bind:class="{'selected': current === n.id}">{{ n }} </button>
<button type="button" #click="page +=1" class="next" v-if="page < evenPosts-1">>></button>
</div>
</div>
</div>
My js:
export default {
el: "#app",
data () {
return {
current: null,
page: 0,
posts: [],
createTitle: '',
createBody: '',
visiblePostID: '',
}
},
watch: {
counter: function(newValue, oldValue) {
this.getData()
}
},
created(){
this.getData()
},
computed: {
evenPosts: function(posts){
return Math.ceil(this.posts.length/10);
},
paginatedData() {
const start = this.page * 10;
const end = start + 10;
return this.posts.slice(start, end);
}
},
methods: {
setCurrent: function(id) {
this.current = id;
},
getData() {
axios.get(`https://jsonplaceholder.typicode.com/posts`).then(response => {
this.posts = response.data
})
},
deleteData(index, id) {
axios.delete('http://jsonplaceholder.typicode.com/posts/' + id)
.then(response => {
console.log('delete')
this.posts.splice(index, 1);
})
.catch(function(error) {
console.log(error)
})
},
addPost() {
axios.post('http://jsonplaceholder.typicode.com/posts/', {
title: this.createTitle,
body: this.createBody
}).then((response) => {
this.posts.unshift(response.data)
})
},
changePost(id, title, body) {
axios.put('http://jsonplaceholder.typicode.com/posts/' + id, {
title: title,
body: body
})
},
}
}
Screenshot of application
add click event #click="page=n" in button
<button #click="page=n" class="item"
v-for="n in evenPosts"
:key="n.id"
v-bind:class="{'selected': current === n.id}">{{ n }} </button>
Codepen : https://codepen.io/anon/pen/bZOROO