Home > Blockchain >  How to adapt the quantity of items to display to viewport's width on Vue?
How to adapt the quantity of items to display to viewport's width on Vue?

Time:10-28

Let's say I have a template that displays a certain quantity of items like so:

<template>
  <div>
    <div v-for="item in items.slice(0, 10)" :key="item" />
  </div>
</template>

How can I show less items on mobile viewport, modifying my slice function ?

I would like to avoid duplicating code and having two lists, one with items.slice(0, 10) and one with items.slice(0, 5), and show one or the other according to a media query because that's not scalable.

I thought about checking user's viewport width on mounted and on page-resize and update the quantity of items that are displayed according to this but I don't find it very clean.

I feel like it's a very common use-case though, is there a good way of doing this ?

CodePudding user response:

I always found that way pretty clunky: using JS for this matter while this is more of a CSS/lazy-loading thing.

I guess you can use this package: https://github.com/scaccogatto/vue-viewports.
By using something like this

<div v-for="item in items.slice(0, this.$currentViewport.label === 'mobile' ? 5 : 10)"
  :key="item"
/>

Inspired by this approach I guess: https://vuetifyjs.com/en/features/breakpoints/

CodePudding user response:

Adding a computed flag to determine the screen width seems a better solution. You can try like this:

created() {
  window.addEventListener("resize", () => {
    this.screenWidth = window.innerWidth
  })
},
computed: {
 isMobile() {
    if (this.screenWidth <= 760) {
      return true
    } else {
      return false
    }
  },
  myItems() {
    return (this.isMobile) ? this.items.slice(0,5) : this.items.slice(0,10)
  }
}

Now you can use the flag anywhere to decide your array lengths on different screen widths.

  • Related