What is the most effective method for displaying or hiding elements based on filtering an array in Vue.js dynamically?

Is there a more efficient way to show/hide elements based on a multiple select in Vue.js? I am currently using methods, but I'm wondering if computed properties could be a better approach. If so, how can this be done?

Here is a sample code sandbox for reference:

https://codesandbox.io/s/dynamic-filter-bp72r?file=/src/pages/Index.vue

<q-select
      filled
      outlined
      dense
      multiple
      options-dense
      v-model="groupBy.fields"
      :options="reporterlocationGroupByFileldOptions"
      label="fields"
      emit-value
      map-options
      option-value="value"
      option-label="name"
      color="orange"
    />

<!-- elements to show/hide -->
    <q-select
      v-if="visibleFilter('province')"
      filled
      outlined
      dense
      options-dense
      v-model="filtering.provinceId"
      :options="provinceOptions"
      label="province"
      emit-value
      map-options
      option-value="id"
      option-label="name"
      class="q-my-sm"
      color="red"
    />
    <q-select
      v-if="visibleFilter('city')"
      filled
      outlined
      dense
      options-dense
      v-model="filtering.cityId"
      :options="cityOptions"
      label="city"
      emit-value
      map-options
      option-value="id"
      option-label="name"
      class="q-my-sm"
      color="green"
    />

My current solution using methods:

data() {
  return {
    filtering: {
      provinceId: '',
      cityId: ''
    },
    reporterlocationGroupByFileldOptions: [
      { name: 'province', orderByDesc: 'province', value: 'province' },
      { name: 'city', orderByDesc: 'city', value: 'city' }
    ]
  }
},
methods: {
    visibleFilter(filterName) {
      var field = this.groupBy.fields.find(x => x === filterName)
        return field ? true : false;
    }
  }

Answer №1

If you want to iterate over the field property in the groupBy property and consolidate your options and v-model under one object, you can modify your code like this:

  filtering: {
    provinceId: {
     value: '',
     option: yourOptions
    },
    cityId: {
     value: '',
     option: yourOptions
    },
    sectionId: {
     value: '',
     option: yourOptions
    },
  },

   <div class="col-xs-12 q-mb-sx" v-for="field in groupBy.fields">
    <q-select
      :key="field"
      filled
      outlined
      dense
      options-dense
      v-model="filtering[field].value"
      :options="filtering[field].option"
      label="green"
      emit-value
      map-options
      option-value="id"
      option-label="name"
      class="q-my-sm"
      color="green"
    />
  </div>

PS: There is a typo in your code, it should be "fields" instead of "fileds".

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

Experiencing the AngularJS [$injector:modulerr] error message despite having flawless code

Despite having code that appears to be correct, I am consistently receiving an [$injector:modulerr] error when working with AngularJS. Check out the updated Fiddle here. I can't seem to figure out what the issue is. Could I be missing something obvi ...

The value of req.files consistently shows as undefined

My issue is with req.files consistently returning undefined. Despite attempting connect-multiparty, body-parser, and express-fileupload, I can't seem to make it work with express-fileupload instead of multer. Can anyone help me troubleshoot this probl ...

Tips for successfully passing import as props arguments in React JS

I am using react-lotties and would like to add different animations to multiple divs by just changing the URL of the lotties As a beginner in React, please be kind :) This is my code snippet : My Lotties Component : import React, { Component } f ...

Tips for achieving JSON formatting with JavaScript or jQuery

To achieve the desired output format, I am required to transform the provided input json. input json: [ { "key a": "value alpha" "key b": "value beta" "key c": "value gamma& ...

The rating script fails to update when multiple ratings are applied simultaneously

Greetings! I am currently in the process of developing a rating script and encountering some issues. At the moment, the script is somewhat functional -> The problem arises when I open two browsers, load image 1 on both, and rate the image in each brow ...

Utilizing Webpack and Typescript for an enhanced DataTables experience: A bespoke JQuery Plugin

I am currently facing an issue while trying to integrate the datatables JQuery plugin with webpack and typescript. While I have successfully set up JQuery with typings and intelliSense, the datatables integration seems to be causing issues. After building ...

Reviewing packages often reveals a multitude of mistakes

I attempted to address some issues in my project by executing npm audit fix Unfortunately, this did not yield significant results. However, when I added the --force flag, the outcome was even worse than before: fix available via `npm audit fix` 10 vulner ...

Efficient method for quickly updating the color scheme of a grid of squares in JavaScript

Currently, I am developing a JavaScript game that features a 2D array of squares with background colors that update each frame. My current approach involves utilizing a borderless DOM table and setting the style.backgroundColor property of each cell every ...

infinite loop issue with beforeRouteEnter

I'm experiencing an issue with Vue Router. The scenario is to load / initially, retrieve data from there, and then navigate to the /chat/:chatId route to display the interface using the :chatId parameter obtained from an API. The routes configured a ...

Unexpected behavior observed when trying to smoothly scroll to internal links within a div, indicating a potential problem related to CSS dimensions and

Within a series of nested div containers, I have one with the CSS property overflow:hidden. My goal is to smoothly scroll to internal links within this specific div using jQuery. The snippet of code below has worked successfully in previous projects: ...

Tips for transferring the asp:Label ID from an asp:CheckBox

I have searched various online forums without success in finding a solution to my issue. I am looking for a way to retrieve an asp:Label's id and pass it to a JavaScript function using the "onclick" event from a nested asp:CheckBox. My goal is to pas ...

Using shortcode to enhance wordpress post content

I am trying to implement a feature similar to the one found at http://jsfiddle.net/theimaginative/gA63t/ within a wordpress post. I have attempted to create a shortcode for inserting this into a post, but I am encountering difficulties. While I have been s ...

I am looking to retrieve a specific input value from a JSON array using JavaScript

I have created an array called 'PROPERTIES' which accepts values like username, password, sid, etc. I am looking to retrieve these entered values using JavaScript. 'PROPERTIES': {'gatewayurl': {'Name': ...

Unprocessed Promise Rejection Alert: The function res.status is not recognized as a valid function (NEXT JS)

When I console.log(response), I see the result in the terminal. However, when I use res.status(200).json(response), I encounter an error in my Next.js project: Not Found in the browser. router.get("/api/backendData", async (req, res) => { dbConne ...

Selenium WebDriver keeps crashing with a newSession error after around 70 seconds of running

Recently, a perplexing error surfaced in my previously functional project without any changes to the code. The sudden appearance of this issue may be attributed to a FireFox update or a dependency failure. To help troubleshoot the abrupt cessation, I added ...

Unable to add or publish text in CKEditor

In my ASP.NET MVC application, I am struggling to post the updated value from a CKEditor in a textarea. Here is the code snippet: <textarea name="Description" id="Description" rows="10" cols="80"> This is my textarea to be replaced with CKEditor ...

Tips for transferring data from a pop-up or modal window to the main window in ASP.NET MVC

Currently, I am in the process of developing a contact form within ASP.NET MVC. This contact form will allow users to easily attach regular files through traditional file and browse functions. Additionally, users will have the option to search for a specif ...

Cannot close the Bootstrap dropdown after selecting an option

I am encountering an issue with a dropdown list that has a select feature using Bootstrap 3.4.1. The problem is that the dropdown remains open after selection and does not close unless I click outside of the list. Here is the HTML code: <div id="c ...

What are the ways in which I can implement that code with a pair of dropdown menus?

Is it possible to use this code with two dropdown menus? Currently, when I reload the page, the first dropdown menu retains its desired state, but the second one does not. Thank you for any help, I apologize for the beginner question as I am new to this am ...

Update a single javascript variable on every rotation of the Bootstrap carousel

Within my website, I have implemented a popin/modal feature using Hubspot Messenger which includes a Bootstrap 3 carousel. Each slide of the carousel displays a different "social embed" such as Facebook or Twitter, and I am looking to adjust the width of t ...