Exploring Vue.js: Enhancing Button Functionality with Select Range

I have a question regarding button selection in a v-for loop. I need to allow users to select options from A to C, as shown in the graphic. Additionally, users should be able to press another button like D.

<menu-item 
   v-for="(item, index) in menu"
   :key="`item_${index}`"
   @click="setMenuItem(index, item.name)"
/>

In my data property selectedItems, I store all selected items when the user clicks on setMenuItem().

The function works correctly when the user selects just one item, but it does not work when selecting a range of items (e.g., from A to C).

My goal is to push each item.name into the selectedItems data property when the user clicks on a range of buttons (e.g., from A to C) by passing the item name as a second argument in setMenuItem().

Check out the graphic for reference: graphic

Answer №1

Before proceeding, it is important to verify whether the index belongs to the specified range.

An option is to define a constant for RangeSelection like this:

const RangeSelection = [0,1,2] // Additional names can be added as required, here 'index' is used.

In your setMenuItem function, include the following check:

setMenuItem(index,name) {
    if(RangeSelection.includes(index)) {
        // Handle range selection
         

    } else {
         // Handle single selection
         this.selectedItems = [];
         this.selectedItems.push(name)
    }

}

Answer №2

When utilizing the setMenuItem method, take note of the parameter index that allows you to designate the chosen value. For instance:

options = [{name: 'a'},{name: 'b'},{name: 'c'}]
selectedValue = [];
setMenuItem(index, name) {
  this.selectedValue = [...options].slice(0, index)
}

Let's say I select menu item b, the selectedValue will display [{name: 'a'},{name: 'b'}]

The issue with the code provided is that it starts from index 0. Therefore, it's essential to include an additional verification step to determine the starting index. You can employ this logic (remember to pass the entire item

@click="setMenuItem(index, item)"
in the component)

setMenuItem(index, item) {
  const start = this.selectedValue.findIndex((selected) => item.name === selected.name)
  this.selectedValue = [...options].slice(start || 0, index + 1)
}

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

Using jQuery Flot to set a target value and visually indicate its position on the graph

I'm currently using the jquery flot plugin to create graphs. My goal is to mark a specific value on the graph by plotting a horizontal line and displaying its exact value. I have already used markings to draw the line, but I am struggling to figure ou ...

The hover effect is not altering the color

$(document).ready(function() { $(window).scroll(function() { var scroll = $(window).scrollTop(); if (scroll > 200) { $(".nav-bg").css({ "background": "#fff", ...

Tips for adjusting the width of a Facebook embedded video within its container using ReactPlayer

Has anyone encountered issues with adding an embedded video to a NextJS app using ReactPlayer and Facebook videos? It seems that Facebook does not support the width="100%" attribute, as it always snaps back to 500px. Interestingly, this works wel ...

Elegant Box 2 - Ascending to the top when clicked

I am excited to share that I am using FancyBox for the first time in my project. This time, I decided to separate the image from the link for a unique user experience. The hover effect works perfectly fine - the issue arises when the link is clicked and th ...

Warning in Next.js: Each element in a list requires a distinct "key" property

Currently, I am in the process of building an e-commerce platform using Nextjs. My current focus is on enhancing the functionality of the myCart page, which serves as a dashboard for displaying the list of items that have been ordered. Below is the code s ...

Challenges Ahead: Navigating Vue CLI and SASS Loader Issues

I primarily work with React and find it quite simple to set up SASS within the framework. However, when I attempted to do the same with Vue, I encountered some difficulties. Upon installing Vue 3 using the CLI and trying to add Node and SASS, I received ...

Is there a way to emphasize a particular day on the calendar obtained from the URL?

I have implemented FullCalendar functionality to enable users to select a specific date, retrieve data from a database, and then reload the page with that data. The page is updated with the selected date in the URL. However, when the page reloads, althoug ...

The d3 hierarchy possesses the capability to compute the average values of child nodes

Looking for a solution with d3 visualization that involves averaging up the value of score on the lowest nodes and dynamically adding that average to the parent node above. It seems like there isn't an easy method in d3 for this task. The desired outc ...

Tips for retrieving the most recent number dynamically in a separate component without needing to refresh the page

Utilizing both the Helloworld and New components, we aim to store a value in localStorage using the former and display it using the latter. Despite attempts to retrieve this data via computed properties, the need for manual refreshing persists. To explore ...

The iron-session package does not export the path ./next/dist from the package

I am encountering an issue while using iron-session. Below is the code snippet causing the error: import { withIronSessionSsr } from 'iron-session/next/dist'; ... export const getServerSideProps = withIronSessionSsr(async function ({ req, r ...

Ways to incorporate data into every page and component of my Nuxt application

In my plugins folder, I have a file named config-ingest.js that contains the following code: import gql from 'graphql-tag' export default ({ app }, inject) => { const client = app.apolloProvider.defaultClient; const apps = gql` que ...

What sets vue.js development apart from minified versions?

When using the minified file, the following code works correctly: <div id="app"> {{ bus.someVar }} -- {{ myVar }} </div> <script> var bus = new Vue({ data: { someVar: 'Variable from BUS' } }) var vm = new Vue({ el: "# ...

The input value in the HTML form was altered momentarily before reverting back to its original state

Researching this topic was quite challenging, but keep reading to find out why. My objective is to detect any changes in a form field so that I can enable the "Save" button. While this seems easy enough, there's a catch. If the user reverts the input ...

Different approach to loading Handlebars template instead of using fs.readFile with res.json in Express

In my efforts to create a straightforward live API endpoint (using res.json()) within an Express 4 application that merges Handlebars templates with data and sends back a string for client-side HTML replacement, I've encountered a challenge. The curr ...

What is the most effective method for integrating JWT for API requests in Nuxt.js?

I am in the process of developing a frontend using nuxt.js and my primary data is obtained from an API. To handle Authorization, I have implemented JSON Web Tokens (JWT) and now I'm looking for the most effective method to inject the JWT into the Requ ...

Show Particular Outcome at the Beginning of Array in ReactJS

I am working with an array of data that contains a list of names, and I need to sort it so that a specific name ("Fav Team") always appears at the top of the list. The array has two fields, homeTeamName and awayTeamName, that may contain this value. How ...

Struggling to grasp the functionality of the Gridsome-Plugin-Firestore, need some guidance

I'm exploring the possibilities of the gridsome-plugin-firestore plugin (). My goal is to utilize this plugin to connect to a simple firestore database collection named news. The news collection contains multiple documents with different fields: con ...

Python Selenium test on AngularJS UI slider implemented

I've been experimenting with setting up a UI slider (Label=ON/OFF, Slider, Apply button) using Angular JS in combination with selenium. Here's an example of the code I've been working on: jsfiddle In my attempts, I tried using the followin ...

Formatting code within an HTML document

I am attempting to customize a stock widget that I obtained from financialcontent.com. My current approach involves using Bootstrap for styling purposes. To incorporate the widget into a div, I found it necessary to embed the script directly within the HT ...

Here is a way to trigger a function when a select option is changed, passing the selected option as a parameter to the function

Is there a way to call a function with specific parameters when the value of a select element changes in Angular? <div class="col-sm-6 col-md-4"> <label class="mobileNumberLabel " for="mobilrNumber">Select Service</label> <div cla ...