How can we adjust the number of items based on the width of the viewport in Vue.js?

Imagine having a template that showcases a specific number of items, like this:

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

How can I adjust the number of displayed items on mobile screens by modifying the slice function?

I want to steer clear of duplicating code and creating separate lists with items.slice(0, 10) and items.slice(0, 5), and then toggling between them based on a media query because it's not sustainable.

One idea I had was to detect the viewport width when the component is mounted or during page resize events, and dynamically update the number of displayed items accordingly, but I'm unsure about the cleanliness of this approach.

This seems like a common scenario, so is there a recommended method for achieving this efficiently?

Answer №1

Personally, I've always found the traditional method a bit cumbersome: resorting to JavaScript for tasks that should be handled by CSS or lazy-loading.

If you're looking for an alternative, you might consider implementing this solution with the help of a package like https://github.com/scaccogatto/vue-viewports.
Here's an example:

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

This approach seems to have drawn inspiration from resources like https://vuetifyjs.com/en/features/breakpoints/

Answer №2

Implementing a computed flag to determine the screen width appears to be a more effective solution. You could implement it like so:

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

With this approach, you can make use of the flag to adjust your array lengths based on different screen widths.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transfer the data in the columns of Sheet1 to Sheet2 and eliminate any duplicates using Google App Script

Is there a way to transfer only unique rows from a SOURCE Spreadsheet to a DESTINATION spreadsheet? Spreadsheet #1 (SOURCE) - This sheet contains ID's and Names, but has duplicate rows. There are over 500k rows in this sheet and it is view-only. Spre ...

AngularJS does not run the code inside the ref once directive

Code within the block of this.verifyUserToken does not execute. It appears that the issue may stem from asynchronous calls, as the data returned is not yet available. I am unsure of how to proceed in handling this. this.verifyUserToken = function(){ ...

Attempting to create a TypeScript + React component that can accept multiple types of props, but running into the issue where only the common prop is accessible

I am looking to create a component named Foo that can accept two different sets of props: Foo({a: 'a'}) Foo({a: 'a', b: 'b', c:'c'}) The prop {a: 'a'} is mandatory. These scenarios should be considered i ...

Step-by-step guide on eliminating the modal post-validation

Newbie in reactjs looking for help with modal validation issue. Goal: Press submit button inside modal, validate, then close the modal. Want to reuse modal for another row. Problem: I'm having trouble making the function work for a new row after ...

Looking for a way to assign the object value to ng-model within a select tag from an array of objects? Also, curious about how to easily implement filters on ng-options?

Here is the HTML code for creating a question template: <body ng-controller="myCtrl"> {{loadDataSubject('${subjectList}')}} {{loadDataTopic('${topicList}')}} <h1 class = "bg-success" style="color: red;text-align: ...

The tagging feature in ui-select isn't working properly, showing an error message that says "Cannot read property 'length' of undefined"

Looking to set up a ui-select for keyword tagging. Initially, when adding a new tag everything works fine, but after removing all tags and adding a new one, I get the error: Cannot read property 'indexOf' of undefined Check out the demo here ...

How can one get rid of a sudden strong beginning?

Recently, I delved into the world of CSS animation and encountered a frustrating issue. I've tried numerous methods and workarounds to achieve a smoothly looping animation without interruptions. Despite my efforts, I have not been able to replicate th ...

Activating autocomplete outcomes via AJAX using Cucumber/Capybara/Selenium

Whenever I try to run my tests, the autocomplete dropdown menu doesn't appear unless I physically click on the search input field. This is a Cucumber test that utilizes Selenium Webdriver, and the data is sourced from the Crafty Clicks Address Autoco ...

Error occurs when attempting to instantiate a class with parameters that do not match any available constructor signatures

I am attempting to encapsulate each instance of router.navigateByUrl within a class function, with the intention of calling that function in the appropriate context. However, I am encountering an error that states 'Supplied parameters do not match any ...

What is the best way to extract the elements within a form using Angular and automatically add them to a list?

Recently, I started learning Angular and decided to create a simple list feature. The idea is to input an item name and price, then click "Add item" to see it added to the list below. I have all the code set up correctly, but for some reason the name and ...

Exploring CouchDB through Ajax to interact with a static website

Is it feasible for my HTML static website to interact with CouchDB using AJAX and retrieve the data without relying on server-side languages like PHP or Python? The CouchDB might be hosted on a different server/domain, so JSONP would need to be utilized. ...

Utilizing Node.js and Mongoose, effortlessly update data in Mongo DB regardless of the existence of the collection

How can I update a field that may or may not exist? I attempted the following code: db.foo.update( { site: '"wisdom'}, { $set: {'club': 'fc barcelona'}}, (upsert=true) ) ...

Issue with vue-router not displaying template for nested routes

My route configuration looks like this: const routes = [{ path: '/', component: Home, children: [ { path: "/health", children: [ { path: 'overview', ...

Closing a Vue modal with a button

Utilizing the bootstrap-vue framework for my modal, I encountered an issue. Upon clicking the button labeled OPEN MODAL, the modal opens with footer buttons OK and CANCEL, which work as expected to close the modal as per bootstrap-vue's default behavi ...

Exploring the variations in method declarations within Vue.js

Today, while working with Vue, I came across an interesting observation. When initially using Vue, there were two common ways to define a method: methods: { foo: () => { //perform some action } } and methods: { foo() { / ...

Customizing the Header Navigation in Vue App.vue Across Various Views

Struggling to find the best approach for managing a header navigation in Vue 2 using Vuex with VueRouter. The main issue is creating a dynamic 'header' type navigation in App.vue. <div id="nav"> <!--Trying to create a dynamic ...

Is ReactJS known for its exceptional performance in rendering large matrices?

Although I have no prior experience with ReactJS, I've heard about a great feature it offers called virtual DOM. It reminds me of the concept of virtual elements in Silverlight where invisible elements are removed from the tree to enhance user-perceiv ...

Is there a way to run a node script from any location in the command line similar to how Angular's "

Currently, I am developing a node module that performs certain functions. I want to create a command similar to Angular's ng command. However, I am facing compatibility issues with Windows and Linux operating systems. Despite my attempts to modify the ...

Remove the JSON key from all array elements while preserving their child elements

I have an array of JSON objects that looks like this: var array_json = [{"my":{"id":144,"price":12500000}}, {"my":{"id":145,"price":13500000}},{"my":{"id":146,"price":13450000}}, {"my":{"id":147,"price":11500000}},{"my":{"id":148,"price":15560000}}] My g ...

Using an AJAX post request will result in receiving an HTML element, especially when an attachment is included with Paperclip

I've created an innovative application where users can share their stories through ajax submissions and engage with other readers by commenting on the stories using ajax as well. The technology stack I'm working with includes Rails 3.0.3, ruby 1. ...