Creating pagination component - vue.js

I am trying to create pagination component. For e.g if my API returns "pages": 9
For example, if I have 9 pages, I want to cut the list at 5 and add three dots like on the image. I want to be able to provide at which index I can cut the list. Whats the best way to do this? I am approaching this wrong?
<div v-for="index in pages" class="flex">
<button>{{index}}</button>
</div>

Assuming you receive cutIndex and apiPages as props to your component, then your template could look something like the following:
<div v-for="page in Math.min(cutIndex, apiPages)" class="flex">
<button>{{page}}</button>
</div>
<template v-if="cutIndex < apiPages">
<div class="flex">
<button>...</button>
</div>
<div class="flex">
<button>{{apiPages}}</button>
</div>
</template>

this code works for me, and here is the key part
<template>
...
<template v-for="index in pages"
v-if="(index < 4 || (length - index) < 3) || Math.abs(index - value) < 2">
<span v-if="index === (length - 2) && value < (length - 4)">
...
</span>
<button #click.prevent="updatePage(index)">
{{ index }}
</button>
<span v-if="(index === 3 && value > 5)">
...
</span>
</template>
...
</template>
the result:
<template>
<nav class="flex items-center justify-center" role="pagination">
<!-- go to previous page -->
<a :key="`${$route.name}-arrow-${value > 1 ? value - 1 : 1}`"
:href="getFullPath(value > 1 ? value - 1 : 1)"
:title="$t('previous_page')"
#click.prevent="updatePage(value > 1 ? value - 1 : 1)"
:disabled="value === 1"
class="arrow pop-btn default rounded-sm"
v-waves>
<i class="mdi-chevron-left mdi"></i>
</a>
<template v-for="index in length"
v-if="(index < 4 || (length - index) < 3) || Math.abs(index - value) < 2">
<span v-if="index === (length - 2) && value < (length - 4)">
...
</span>
<a :href="getFullPath(index)"
:title="$t('page_index', {index: index})"
#click.prevent="updatePage(index)"
class="pop-btn number default rounded-sm"
:class="{
'active': index === value
}"
v-waves>
{{ index }}
</a>
<span v-if="(index === 3 && value > 5)">
...
</span>
</template>
<!-- go to next page -->
<a :href="getFullPath(value === length ? value : value + 1)"
:title="$t('next_page')"
#click.prevent="updatePage(value === length ? value : value + 1)"
:disabled="value === length"
class="arrow pop-btn default rounded-sm"
v-waves>
<i class="mdi-chevron-right mdi"></i>
</a>
</nav>
</template>
<script type="text/javascript">
export default{
emits: ['update:value],
props: {
length: {
required: true,
type: Number
},
// the page filter
value: {
required: true,
type: Number
}
},
methods: {
updatePage(index){
this.$emit('update:value', index);
},
getFullPath(page){
let query = {...this.$route.query};
page === 1 ? delete query.page : query.page = page;
return this.$router.resolve(
this.r({
query: query,
name: this.$route.name,
params: this.$route.params
})
).href;
}
}
}
</script>
by the way, <a> may better than <button> for SEO

Related

How to first show an element, then perform a function to change the style of this element vue.js

When the button is clicked, the onclick event is triggered and the function is executed
descriptionShown: function (num) {
if (this.visibleNumber === num) {
this.isShown = !this.isShown;
} else {
this.isShown = true;
this.visibleNumber = num;
}
if(this.isShown)
this.textareaResize(num);
},
after isShown = true, the textarea component should be redrawn, since there is
v-if="{{ newRecord.originalRecordId }} == visibleNumber && isShown"
<template v-if="{{ newRecord.originalRecordId }} == visibleNumber && isShown">
<ul class="list-group" :style="{ display: 'block' }" >
<li class="list-group-item"><textarea id="textarea-{{ newRecord.originalRecordId }}" readonly>{{ newRecord.originalRecordText }}</textarea></li>
</ul>
</template>
<template v-else>
<ul class="list-group" :style="{ display: 'none' }" >
<li class="list-group-item"><textarea id="textarea-{{ newRecord.originalRecordId }}" readonly>{{ newRecord.originalRecordText }}</textarea></li>
</ul>
</template>
How do I make it so that the redraw occurs first(via v-if), and then the function to change the size of the textarea is executed? And then it turns out that first there is a change in size(0 to 0), then only the element is displayed

Cannot read property 'focus' of undefined in VUE When setting focus to button

I am new to vue I have component which if the endpoint fails, calls my generic 'Error' modal. All this is working fine but I keep getting the following error:
Cannot read property 'focus' of undefined
This only happens for the else part of my method function.
For this specific issue is I my 'failedPrcess' equals any of the following, this is when I get is, all others are fine:
existOrderSearchProdOrders
stockSearchStockLevels
cartFetchCouriers
Code
<template>
<div class="modal fade danger-modal" id="errorModal" tabindex="-1" role="dialog" aria-labelledby="errorModalTitle" aria-hidden="true"
data-keyboard="false" data-backdrop="static" style="z-index: 99999">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content danger-modal-content">
<div class="modal-header danger-modal-headerfooter">An error has occurred</div>
<div class="modal-body">
<p v-if="failedProcess === 'appGetAccount' || failedProcess === 'existOrderSearchProdOrders' || failedProcess === 'stockSearchStockLevels'
|| failedProcess === 'cartFetchCouriers'">
{{ contactTxt | capitalize }}
</p>
<p v-else-if="errorCount < 3">If the error continues, {{ contactTxt }}</p>
<p v-else>As the error has continued, {{ contactTxt }}</p>
<p>
<b>
01234 567890
<br />
Open from 00:00 to 07:00
</b>
</p>
<p>Advising of what you were doing when the error occurred.</p>
</div>
<div class="modal-footer danger-modal-headerfooter">
<a v-if="failedProcess === 'appGetAccount'" ref="logoutButton" class="btn btn-primary" :class="logoutButtClicked" #click="logoutClicked = true" href="/site/logout">
<span v-if="!logoutClicked" id="logoutButtonLabel">Logout</span>
<span v-else id="logoutSpinner">
<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
Logging out
</span>
</a>
<router-link v-else-if="failedProcess === 'fetchOrderReportDetails'" to="/review" tag="button"
ref="existOrdersButton" class="btn btn-primary" type="button" data-dismiss="modal" #click.native="closeButton">
Return to existing orders
</router-link>
<button v-else-if="errorCount < 3 && (failedProcess !== 'productsFetchProducts' && failedProcess !== 'existOrderSearchProdOrders'
&& failedProcess !== 'stockSearchStockLevels' && failedProcess !== 'cartFetchCouriers')" ref="closeButton" class="btn btn-primary"
type="button" data-dismiss="modal" #click="closeButton">
Close
</button>
<router-link v-else to="/" tag="button" ref="homeButton" class="btn btn-primary" type="button" data-dismiss="modal" #click="closeButton">
Return to homepage
</router-link>
</div>
</div>
</div>
</div>
</template>
<script>
import * as params from '../params';
export default {
name: "ErrorModal",
data() {
return {
contactTxt: 'please contact us on:',
errorCount: 0,
failedProcess: '',
}
},
mounted() {
VueEvent.$on('show-error-modal', (failedProcess) => {
if (this.failedProcess !== failedProcess) {
this.errorCount = 0;
}
this.failedProcess = failedProcess;
$('#errorModal').modal('show').on('shown.bs.modal', this.focus);
});
},
methods: {
focus() {
if (this.failedProcess === 'appGetAccount') {
this.$refs.logoutButton.focus();
} else if (this.failedProcess === 'fetchOrderReportDetails') {
this.$refs.existOrdersButton.$el.focus();
} else if (this.errorCount < 3 && this.failedProcess !== 'productsFetchProducts') {
this.$refs.closeButton.focus();
} else {
this.$refs.homeButton.$el.focus();
}
},
}
}
</script>`enter code here`
I've tried using v-if before and I also had similar problems and the best solution I found was, instead of using v-if/v-else-if/v-else, use v-show instead to perform conditional rendering.
Also, as the Vue.js doc says:
Generally speaking, v-if has higher toggle costs while v-show has higher initial render costs. So prefer v-show if you need to toggle something very often, and prefer v-if if the condition is unlikely to change at runtime.

Error setting default accordion item in class condition

In my laravel 5.7 / Vuejs ( vue": "^2.6.10" ) / "bootstrap": "^4.3.1" application
using accordion I want in debugging purpose show 1 block openec with template like:
<div :id="'collapse'+nextStateWithRegion.id" v-bind:class="'collapse'+{ ' show' : nextStateWithRegion.id == debugging_state_id }" :aria-labelledby="'heading'+nextStateWithRegion.id"
data-parent="#accordion_hostels_by_location">
<div class="card-body">
<!--{{ nextStateWithRegion.regionsOfStateArray }}-->
<ul>
<li v-for="nextRegionOfState, index in nextStateWithRegion.regionsOfStateArray" :key="nextRegionOfState.id">
<!--nextRegionOfState::{{ nextRegionOfState }}-->
<router-link :to="{ name: 'hostelsByRegion', params: { region_id: nextRegionOfState.id, state_id : nextRegionOfState.state_id } }"
class="nav-link">{{ nextRegionOfState.name }}
<small>( {{ nextRegionOfState.related_common_hostels_count }} hostels with {{ nextRegionOfState.related_featured_hostels_count }}
featured)</small>
</router-link>
</li>
</ul>
</div>
</div>
but result is different, as I see not ‘ show’ string added to the class, but ‘[object Object]’ :
https://imgur.com/a/YWenuxh
Which way is correct ?
Thanks!

How to set class to child element inside v-for loop

I need some help, I have v-for loop which outputs elements of array referenceDetailsDocumentsData, I need to check at the same time if the id of this element exists in another array documentsData, in this case I need to add custom class to child of this element.
<div class="loading-doc-item"
v-for="referenceDetails in referenceDetailsDocumentsData"
:key="referenceDetails.id">
<div class="loading-doc-show">
{{ referenceDetails.name }}
<span class="upload-status" v-if="checkUploadedDocuments(referenceDetails.id)">
<i class="fa fa-check-circle"></i>
</span>
<span class="upload-status" v-else>
<i class="fa fa-check"></i>
</span>
</div>
</div>
methods() {
checkUploadedDocuments(id) {
return this.documentsData.filter(item => item.id === id);
}
}
In my case, I am getting an error
Error in render: "TypeError: this.documentsData.filter is not a
function"
Your logic is wrong - the method checkUploadedDocuments will return Array but it must return Boolean.
<div class="loading-doc-item"
v-for="referenceDetails in referenceDetailsDocumentsData" :key="referenceDetails.id">
<div class="loading-doc-show">
{{ referenceDetails.name }}
<span class="upload-status">
<i class="fa"
:class="{documentsData && documentsData.length &&
documentsData.findIndex(item => item.id === referenceDetails.id) !== -1
? 'fa-check-circle' : 'fa-check'}"></i>
</span>
</div>
</div>

Vue - check if you are on the last prop of a v-for loop

If I have the following data property:
person: {name: 'Joe', age: 35, department: 'IT'}
And wanted to loop through and output it as follows:
name: Joe, age: 35, department: IT
So far I have:
<span v-for="(val, key) in person">{{key}}: {{val}}, </span>
But this displays:
name: Joe, age: 35, department: IT,
with an extra comma on the end, how can I have it detect that it's the last prop and not show the comma? I thoughta v-show or v-if may be the solution but can't quite figure out how to make it work.
Here is one way.
<span v-for="(val,key,index) of person">
key: {{key}}, val: {{val}}, index: {{index}}
<span v-if="index != Object.keys(person).length - 1">, </span>
</span>
Here's a solution if you're looping through an array, rather than an object:
<div id="app">
<div v-for="(item, index) in items">
<div v-if="index == items.length - 1">yes</div>
{{ item }}, {{ index }}
</div>
</div>
You can also "cheat" by inserting the comma before each item, as it's easier to check for the first item (index !== 0).
<span v-for="(val, key, index) in person">
<span v-if="index !== 0">, </span>
{{key}}: {{val}}
</span>
You can do that with a computed to see if the current index (third parameter forv-if) is the last property:
computed: {
last(){
return Object.keys(this.person).length-1;
}
}
Then in your v-for:
<span v-for="(val, key, index) in person">{{key}}: {{val}}<span v-if="index !== last">, </span> </span>
Here's the JSFiddle: https://jsfiddle.net/wv2ujxvn/
This also works:
<span v-for="(value,key) in persons" :key='key'>
{{key}}: {{val}}
<span v-if="key+1 != persons.length">, </span>
</span>
A pity there is no shortcut provided by Vue.
I personally prefer using a small CSS:
<div class="list">
<span>Item 1</span>
<span>Item 2</span>
<span>Item 3</span>
</div>
.list span:not(:last-child)::after {
content: ',';
}
If you want to store the knowledge about this pattern in code instead of on Stack Overflow, you could create a component like this:
<template>
<span v-if="show"><slot></slot></span>
</template>
<script>
export default {
name: 'separator',
props: ['items', 'index'],
computed: {
show () {
return this.index !== (Array.isArray(this.items) ? this.items : Object.keys(this.items)).length - 1
}
}
}
</script>
This doesn't necessarily make the code shorted, but easier to remember:
<span v-for="(val, key, index) of person">key: {{key}}, val: {{val}}
<separator :items="person" :index="index">, </separator>
</span>