Minimize Pagination Vue.js - vue.js

I have a pagination and it looks like this: < 1 2 3 4 5 6 7 8 9 >
But it's too big, so I need to display them like this: < 1 2 3 4 ... 21>
This is my template:
ul.pagination.float-right
li.page-item
a.page-link(v-on:click="prevPage()")
i.icon.ion-ios-arrow-back
li(v-for="n in numberOfPages")
a.page-link(#click="goToPage(n)", :limit="3" :style= "[actualPage == n && {backgroundColor: '#d3d3d3'}]") {{n}}
li.page-item
a.page-link(v-on:click="nextPage()")
i.icon.ion-ios-arrow-forward
and my script:
data () {
return {
numberOfPages: 0,
roles: [],
rolesInPage: [],
actualPage: 1,
elementsByPage: 10,
prevPage () {
if (this.actualPage > 1) {
this.actualPage = this.actualPage - 1
}
const from = this.elementsByPage * (this.actualPage - 1)
this.rolesInPage = this.roles.slice(from, from + 10)
},
nextPage () {
if (this.actualPage < this.numberOfPages) {
this.actualPage = this.actualPage + 1
}
const from = this.elementsByPage * (this.actualPage - 1)
this.rolesInPage = this.roles.slice(from, from + 10)
},
getNumberOfPages () {
return Math.ceil(this.roles.length / this.elementsByPage)
},
goToPage (page) {
this.actualPage = page
const from = this.elementsByPage * (this.actualPage - 1)
this.rolesInPage = this.roles.slice(from, from + this.elementsByPage)
},
Any help will be much appreciated

I wrote a basic solution, but needs some improvements and you'll need to validate in your frontend what's the limit of pages to show and place those dots between them.
The basic solution
That function returns an array with just the indexes you want and an extra index with the total of pages you already had.

Related

Not sure how LoadItems work in the React-Native-Calendars example

I'm trying to use the react-native-calendars library in my code.
I'm trying to understand this snipped of the code here
loadItems = (day: DateData) => {
const items = this.state.items || {};
setTimeout(() => {
for (let i = -15; i < 85; i++) {
const time = day.timestamp + i * 24 * 60 * 60 * 1000;
const strTime = this.timeToString(time);
if (!items[strTime]) {
items[strTime] = [];
const numItems = Math.floor(Math.random() * 3 + 1);
for (let j = 0; j < numItems; j++) {
items[strTime].push({
name: 'Item for ' + strTime + ' #' + j,
height: Math.max(50, Math.floor(Math.random() * 150)),
day: strTime
});
}
}
}
const newItems: AgendaSchedule = {};
Object.keys(items).forEach(key => {
newItems[key] = items[key];
});
this.setState({
items: newItems
});
}, 1000);
}
The entire code snip can be found here: https://gist.github.com/jonasgroendahl/f5e938cdf0a77c2e1509ded22630ba7d
Currently I know this part of the code generates an item for everyday. I'm looking to change this up but I'm not sure what happening line by line. If anyone can please break this down and explain it to me would be great. Thanks.

How could I change the value of this.buttonState in this scenary?

I'm having issues in this process . First is that I have a button in disabled state(true) and I need to change that value to false when the video is uploaded . I have this scenary and I think I got a windows object inside the changing method . Any idea, help please . I'm getting undefined value for the variable.
data: () => ({
buttonState: true} }),
changeBehavior() {
let self
(function () {
const input = document.getElementById('uploader')
self = this
console.log(this)
const changing = ({ target: { files } }) => {
if (input.files.length > 0) {
// self.buttonState = false
const video = document.getElementById('output-video')
video.src = URL.createObjectURL(files[0])
}
}
input.addEventListener('change', changing)
})()
const au = document.getElementById('output-video')
au.onloadedmetadata = () => {
const hidden = document.getElementById('hiddenSlider')
hidden.removeAttribute('hidden')
const muteHidden = document.getElementById('muteHidden')
muteHidden.removeAttribute('hidden')
self = this
self.range = [0, au.duration]
this.max = au.duration
const secNum = parseInt(au.duration, 10)
let hours = Math.floor(secNum / 3600)
let minutes = Math.floor((secNum - (hours * 3600)) / 60)
let seconds = secNum - (hours * 3600) - (minutes * 60)
if (hours < 10) {
hours = '0' + hours
}
if (minutes < 10) {
minutes = '0' + minutes
}
if (seconds < 10) {
seconds = '0' + seconds
}
document.getElementById('renderizado').innerHTML =
hours + ':' + minutes + ':' + seconds
}
},
<v-btn
id="run"
class="accent-3 blue ml-15"
dark
#click="$refs.inputUpload.click()"
>
<input
v-show="false"
id="uploader"
ref="inputUpload"
accept=".mkv,video/*"
type="file"
#click="changeBehavior"
>
Select to Upload Video
</v-btn>
<v-btn
id="doTrimming"
block
class="accent-3 blue mt-5"
dark
:disabled="buttonState"
#click="cutIt"
>
Trim Video Now
</v-btn>
Where you define self you need to assign this to it then.
changeBehavior() {
const self = this;
const callback = function() {
// now you can access the vue instance when in another functions scope
self.buttonState = true;
}
}

i18next.services.pluralResolver.addRule returns undefined for addRule

import i18next from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
const locales = ['en-GB', 'pl-PL'];
export const supportedLanguages = locales;
const localeResources = {
'en-GB': {
common: require('./locales/en-GB/common.json'),
},
'pl-PL': {
common: require('./locales/pl-PL/common.json'),
},
};
const frozenLocales = Object.freeze(locales);
export function localesImmutable() {
return frozenLocales;
}
const fallbackLanguages = {
pl: ['pl-PL'],
default: ['en-GB'],
};
i18next.services.pluralResolver.addRule('pl', {
numbers: [1, 2, 3],
plurals: function (n) {
return Number(
n === 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2
);
},
});
const i18n = i18next;
i18n.use(LanguageDetector).init({
resources: localeResources,
fallbackLng: fallbackLanguages,
ns: 'common',
defaultNS: 'common',
react: { wait: true },
debug: false,
cache: { enabled: true },
});
export default i18n;
I followed this link to override plural rule for my project.
When I try to override the plural rule, I can't. pluralResolver doesn't seem to have addRule method. I get TypeError: Cannot read property 'addRule' of undefined. What am I missing? The translation is for Polish plurals.
You should call addRule only after the init is done.
i18n
.use(LanguageDetector)
.init({
resources: localeResources,
fallbackLng: fallbackLanguages,
ns: 'common',
defaultNS: 'common',
react: { wait: true },
debug: false,
cache: { enabled: true },
})
.then(() => {
// this called after the init finished
i18n.services.pluralResolver.addRule('pl', {
numbers: [1, 2, 3],
plurals: function (n) {
return Number(
n === 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2
);
},
});
});

Vue Leaflet Get Color Function

I am using VueLeaflet to create a map like in this example: https://vue2-leaflet.netlify.com/examples/geo-json.html
I like to add some colors to the polygons like in this example: https://leafletjs.com/examples/choropleth/
This is my try here: https://codesandbox.io/s/old-framework-mlc7b
getcolorFunction(d) {
return d > 1000
? "#800026"
: d > 500
? "#BD0026"
: d > 200
? "#E31A1C"
: d > 100
? "#FC4E2A"
: d > 50
? "#FD8D3C"
: d > 20
? "#FEB24C"
: d > 10
? "#FED976"
: "#FFEDA0";
},
styleFunction() {
const fillColor = this.fillColor; // important! need touch fillColor in computed for re-calculate when change fillColor
return () => {
return {
weight: 2,
color: "#ECEFF1",
opacity: 1,
fillColor: getColor(feature.properties.sales),
fillOpacity: 1
};
};
},
onEachFeatureFunction() {
if (!this.enableTooltip) {
return () => {};
}
return (feature, layer) => {
layer.bindTooltip(
"<div>Name Province:" +
feature.properties.varname_1 +
"</div><div>Sales: " +
feature.properties.sales +
"</div>",
{ permanent: false, sticky: true }
);
};
}
},
How could I Get work that function getColor in Vue.js ?
onEachFeatureFunction() {
return (feature, layer) => {
layer.options.fillColor = this.getcolorFunction(
feature.properties.sales
?feature.properties.sales
: 0
);
layer.on("click", function (e) {
console.log(e, feature);
})
};
}

Improve the speed of a realm query in react-native?

I have something like the following code in my react native app to set up mock/test data for performance tests.
realm.write(() => {
const max = 120;
for(let x=1; x<=max; x++)
{
realm.create('Product', {productId:x});
}
for(let x=1; x<=max; x++)
{
for(let y=x; y<=max; y++)
{
for(let z=y; z<=max; z++)
{
realm.create('Compatibility', {
result: 'Y '+x+' '+y+' '+z,
products: [
realm.objects('Product').filtered('productId = '+x)[0],
realm.objects('Product').filtered('productId = '+y)[0],
realm.objects('Product').filtered('productId = '+z)[0]
]
});
}
}
}
});
class Product {}
Product.schema = {
name: 'Product',
primaryKey:'productId',
properties: {
productId:'int'
}
};
class Compatibility {}
Compatibility.schema = {
name: 'Compatibility',
properties: {
result: {type: 'string'},
products: {type: 'list',objectType:'Product'},
}
};
This means the Products object has 120 records and the Compatibility object has 1.7 million records.
When I run the query realm.objects('Compatibility').filtered(products.productId = 3 AND products.productId = 25 AND products.productId = 97), it takes about 15 seconds to run on my old HTC Desire 510 and my Huawei Nova Plus. This is too slow.
Is there a way to improve the speed of the query? For example, can you index the columns or something?
First of all there is indexing in realm and primaryKeys are indexed already. So indexing in this scenario won't help you. But I think I have an idea of how you could get faster the process.
At the last for loop you are doing 3 queries. 2 of them happens unnecessarily I think since x and y values going to be same for 120 z values. If you implement something like the code below, it might help a little bit with the performance I think.
let productX;
let productY;
let productZ;
for (let x = 1; x <= max; x++)
{
productX = realm.objects('Product').filtered('productId = ' + x)[0];
for (let y = x; y <= max; y++)
{
productY = realm.objects('Product').filtered('productId = ' + y)[0];
for (let z = y; z <= max; z++)
{
productZ = realm.objects('Product').filtered('productId = ' + z)[0];
realm.create('Compatibility',
{
result: 'Y ' + x + ' ' + y + ' ' + z,
products: [ productX, productY, productZ]
});
}
}
}
A second though;
This might be a really bad idea and can be a terrible practice but I'm going to give as a thought practice.
If you are always doing query with 3 different productIds, you can create a string with all tree in a single property and query only that. This way you can use indexing.
Example
class Compatibility {}
Compatibility.schema = {
name: 'Compatibility',
properties: {
result: {type: 'string'},
productQueryHelper: { type: 'string', indexed: true }
products: {type: 'list',objectType:'Product'},
}
};
realm.create('Compatibility',
{
result: 'Y ' + x + ' ' + y + ' ' + z,
productQueryHelper: `${x}&${y}&${z}` // you can use any other separator that isn't possible to be in productId
products: [
realm.objects('Product').filtered('productId = ' + x)[0],
realm.objects('Product').filtered('productId = ' + y)[0],
realm.objects('Product').filtered('productId = ' + z)[0]
]
});
realm.objects('Compatibility').filtered('productQueryHelper = "3&25&97"')
Try to set your primary keys as indexed.
Btw I've never had problems with performance using Realm.
Nowadays I'm using Realm in a scenario to manage my notifications. I have a lot of queries running at some time and this never hurt the performance.
class Product {}
Product.schema = {
name: 'Product',
primaryKey:'productId',
properties: {
productId: { type: 'int', indexed: true }
}
};
class Compatibility {}
Compatibility.schema = {
name: 'Compatibility',
properties: {
result: {type: 'string'},
products: {type: 'list',objectType:'Product'},
}
};