Employing a pair of interdependent v-select components to prevent any duplicate entries

I am currently working with two v-select boxes that share similar data. In my scenario, I extract attachments from an email and load them into an array. The issue I encountered is that the first select box should only allow the selection of one document, while the second select box should only display items that have not been chosen in the first v-select box. Below is a snippet of my template code:

                            <v-select v-model="selectedResponses"
                                  :items="attachments"
                                  item-value="id"
                                  item-text="name"
                                  label="First Document"
                                  persistent-hint
                                  filled
                                  chips
                                  return-object></v-select>            
                        <v-select v-model="selectedSupportingDocs"
                                  :items="availableSupportingDocs"
                                  item-value="id"
                                  item-text="name"
                                  label="Additional Documents"
                                  persistent-hint
                                  multiple
                                  filled
                                  chips
                                  return-object></v-select>

To address this issue, I decided to make the items for the second v-select box a computed property by removing the selected value in the first v-select box. However, the problem I'm facing is that whatever I choose in the first box becomes the only available option in the second v-select box. It seems like the splice() function is not working as expected.

            computed: {
            availableSupportingDocs() {
                if (this.selectedResponses == null) return this.attachments;

                for (let i = 0; i < this.attachments.length; i++) {
                    if (this.selectedResponses.id === this.attachments[i]["id"]) {
                        console.log(this.attachments[i]["name"])
                        console.log(this.attachments.slice().splice(i, 1))
                        return this.attachments.slice().splice(i,1)
                    }
                }

                return this.attachments
            }
        },

Answer №1

When using the .splice() method, keep in mind that it will alter the original array and return a new array with the removed values:

const arr = [1,2,3,4]
const splicedOff = arr.splice(2,1)

const s = JSON.stringify
console.log('spliced:', s(splicedOff), 'remaining:', s(arr))

It is important to note that only the element you didn't want to include will be returned.

There are a couple of ways to address this issue:

  • Assign the modified array to a new variable before using .splice(), then return that variable
const newAttachments = this.attachments.slice()
newAttachments.splice(i,1)
return newAttachments
  • Alternatively, you can utilize .filter()
return this.attachments.filter((_,ix) => i !== ix)

By using filter(), you can eliminate the need for an outer loop:

availableSupportingDocs() {
  return !this.selectedResponses 
  ? this.attachments
  : this.attachments.filter((attachment) => this.selectedResponses.id !== attachment.id)
}

In your comments, you mentioned that when selectedResponses change, you may need to update the value of selectedSupportingDocs. This can be achieved through a watcher or an event handler.

A watch function would look like this:

watch: {
  selectedResponses: function () {
    if(this.selectedResponses?.id === this.selectedSupportingDocs.id) {
      this.selectedSupportingDocs = null
    }
  },
},

For an event handler approach, add a @change to the v-select:

<v-select
  v-model="selectedResponses"
  :items="attachments"
  ...
  @change="adjustSupportingDocsSelection"
/>

The corresponding method would be placed in the component methods:

methods: {
  adjustSupportingDocsSelection(){
    // same as above
  }
}

Personally, I lean towards using the event handler because it is more explicit. The watcher is advantageous if there are other mechanisms that could change selectedResponses, covering all scenarios. Choose the approach that aligns best with your preferences.

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

Mastering the art of square bracket destructuring in React through deep comprehension of the concept

import React, { useEffect, useState } from 'react' import { Text } from 'react-native' export default function Counter() { const [count, setCount] = useState(0) useEffect(() => { const id = setInterval(() => setCount((co ...

Enhance Your Highcharts Funnel Presentation with Customized Labels

I am working on creating a guest return funnel that will display the number of guests and the percentage of prior visits for three categories of consumers: 1 Visit, 2 Visits, and 3+ Visits. $(function () { var dataEx = [ ['1 Vis ...

The image is being loaded onto the canvas and is being resized

Currently, I am facing an issue with loading images into a canvas element as the image seems to be scaled in some way. To provide some context, I have multiple canvases on my webpage and I want to load images into them. Since the dimensions of the canvas ...

Identify the row containing a value of null using jQuery (functionality not performing as anticipated)

Whenever the user clicks on the GetData button, I retrieve JSON data and display it in an HTML table similar to the demo below. Demo: https://plnkr.co/edit/I4XYY6CZohf7IS6wP8dR?p=preview There are instances where the value can be null, such as the loanNu ...

Unable to fetch Title from Strapi

I have a collection type named posts with the following values: To access the API, I have a file in my lib folder that contains the following code: export async function getPosts() { var api_base_url = process.env.API_BASE_URL; const response = await fetc ...

We were unable to load the resource because the server returned a 404 (Not Found) error. The EnterpriseMaster/BindNatureofAssignment feature is not functioning properly after being published

While the code is working perfectly fine on localhost, as soon as I publish it I encounter an error that prevents the table from loading. EnterpriseMaster/BindNatureofAssignment:1 Failed to load resource: the server responded with a status of 404 (Not ...

Over time, memory usage increases significantly in JS applications that heavily rely on Ajax

I've noticed significant memory leaks in an app I'm currently developing. Despite its lack of complexity, the app requests approximately 40kb of JSON data from the server every 15 seconds. This data is then used to generate a table on the page. A ...

Error message displayed: "An error occurred while processing the VueJS InertiaJS Uncaught (in promise) TypeError. It seems that the property 'search'

Currently, I am working on a Vue JS project with Inertia. One of the features I am implementing is a list that allows users to filter by name. data() { return { selectedUser: this.value, selected: null, search: & ...

The Vue/Nuxt application displays content duplication on each page, rendering the content twice without duplicating the components

I recently delved into Vue/Nuxt programming and worked through a tutorial on adding a blog, which I then customized for my website. Everything functions perfectly except that the content is rendering twice. It goes from rendering NavPage (component) > c ...

Dynamic row additions causing vanishing rows in the table due to JS/jQuery implementation

I am currently facing an issue while trying to create a table where I can add rows dynamically. Despite looking at various solutions on this topic, none of them seem to resolve the problem I am encountering. The newly added rows disappear immediately after ...

Will a notification box appear upon submission indicating success or failure?

After the submit button is clicked, I need a pop-up box to display either a successful or failed message. Then confirm the message by clicking OK. Currently, I am seeing an "undefined" pop-up followed by a failed message pop-up. Can someone please assist m ...

The surprising behavior of Rails rendering partials even when they are commented out has

I'm intrigued by how Rails 5 handles partials and if there might be a hidden problem I haven't encountered yet. On my current page, I have two partials - one that is included in the HTML itself, and another that is supposed to render inside an aj ...

What exactly entails static site generation?

I have been exploring the concept of static site generation (SSG). The interesting question that arises is how SSG can fetch data at build time. In my latest application, I implemented an event handler to retrieve data based on a user's search keyword ...

Vue.js: Utilizing async/await in Vue.js results in an observer being returned

Currently, I'm attempting to retrieve data from an API and store it in an array. The issue arises when I try to log the response data from the API - the data is displayed just fine. I assign the value of a variable to the data obtained from awaiting t ...

Encountering a problem while creating a Page Object in webdriver.io - getting the error "setValue is not a function" or "cannot read property 'setValue' of undefined"

While working on a webdriver.io automation project, I encountered an issue with recognizing objects in my page object file (login.po.js) when calling them in the test spec file (test.spec.js). The error message displayed is LoginPage.username.setValue is n ...

What is the best way to customize a component in a view?

<template> <div class="about"> <Header /> <h1>Welcome to the dashboard page</h1> </div> </template> <script> import Header from "../components/layout/Header.vue"; export default { name: "dashb ...

Place a request for the Material UI switch on the platform

I'm currently in the process of constructing a switch that gets its checked value from the data retrieved from the backend. When a user toggles it, a PUT request is sent to the backend for updating the choice. Although I've made progress on it, ...

Tips for successfully incorporating a jQuery plugin into your React project

I'm attempting to incorporate the Air Datepicker library by t1m0n into my React application, but I'm encountering difficulties. import React from 'react'; import AirDatepicker from 'air-datepicker'; class Datepicker extend ...

How do I prevent my image slider from scrolling to the top of the page when I click next or prev?

<script> export default { name: "ImageSlider", data() { return { images: [ "https://cdn.pixabay.com/photo/2015/12/12/15/24/amsterdam-1089646_1280.jpg", "https://cdn.pixabay.com/photo/2016/02/17/2 ...

Getting a 406 (Not acceptable) error when trying to perform an AJAX action in Rails 4

I am attempting to automatically refresh a specific partial view every 60 seconds on the homepage. To make it easier to manage, I have divided the actions into two routes. However, I am encountering an issue with the respond_to block and could use some ass ...