Vue.js/Vuetify - Dynamically filter select options based on another select value

Is there a way to filter data in order to populate one select based on the selection made in another select? For example, if I choose a state from one select, can I have a second select loaded with all cities from that specific state? I am using vue.js and vuetify as my framework, with the v-select component. I have attempted to set up a computed property, but the second select does not load the data even after making a selection from the first one.

HTML

Vue.use(Vuetify);

var app = new Vue({
  el: '#app',
  data() {
    return {
      items: {
        home_id: null,
      },
      support: {
        home_province: '',
      },
      options: {
        opt_province: [{
          text: 'British Columbia',
          value: 1
        }, {
          text: 'Ontario',
          value: 2
        }],
        opt_city: [{
          text: 'Vancouver',
          value: 1,
          dependency: 1
        }, {
          text: 'Surrey',
          value: 1,
          dependency: 1
        }, {
          text: 'London',
          value: 1,
          dependency: 2
        }, {
          text: 'Toronto',
          value: 1,
          dependency: 2
        }]
      }
    }
  },
  computed: {
    filteredData() {
      var city = this.options.opt_city;
      var province = this.support.home_province;
      for (var i = 0; i < city.length; i++) {
        if (city[i].dependency != province.value) {
          city.splice(i);
        }
      }
      return city;
    },
  }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<link href="https://unpkg.com/vuetify/dist/vuetify.min.css" rel="stylesheet" />
<script src="https://unpkg.com/vuetify/dist/vuetify.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons' rel="stylesheet" type="text/css">
<div id="app">
  <v-app>
    <v-card class="grey lighten-4 elevation-0">
      <v-card-text>
        <v-container fluid>
          <v-layout row wrap>
            <v-flex xs4>
              <v-flex>
                <v-subheader>Origin Province</v-subheader>
              </v-flex>
              <v-flex>
                <v-select :items="options.opt_province" v-model="support.home_province" label="Select" class="input-group--focused" single-line>
                </v-select>
              </v-flex>
            </v-flex>
            <v-flex xs4>
              <v-flex>
                <v-subheader>Origin City</v-subheader>
              </v-flex>
              <v-flex>
                <v-select :items="filteredData" v-model="items.home_id" label="Select" class="input-group--focused" single-line autocomplete>
                </v-select>
              </v-flex>
            </v-flex>
          </v-layout>
        </v-container>
      </v-card-text>
    </v-card>
  </v-app>
</div>

Here is the link to the jsfiddle: https://jsfiddle.net/vcmiranda/tkkhwq6m/

Thank you.

Answer №1

To achieve your goal, you need to apply a filter to the city options list.

Modify your filteredData computed property to

filteredData() {
  let cities = this.options.opt_city;
  return cities.filter(city => city.dependency === this.support.home_province);
}

Check out the updated demo.

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

specific css styles only for Safari and Internet Explorer

Imagine a scenario where I have a div with the class 'x': <div class = 'x' /> This div has some CSS properties and what's interesting is that it appears differently in Safari and the latest version of IE compared to other ...

Activating Cors Support on Firefox

When working with AngularJS, I wrote the following code to make an API call: $http({ method: 'GET', url: 'https://www.example.com/api/v1/page', params: 'limit=10, sort_by=created:desc', //h ...

Tips for combining values with Reactive Forms

Is there a way to merge two values into a single label using Reactive Forms without utilizing ngModel binding? <label id="identificationCode" name="identificationCode" formControlName="lb ...

Guide on adjusting the darkness of a MaterialUI Avatar component image and adding text to it

I'm currently working with the Avatar component from Material UI along with Tailwind CSS. I found that by simply adding the image URL to the src, it displays the avatar successfully. <Avatar alt="Cindy Baker" src="https://mui.com/sta ...

Is there a way to retrieve the disabled drop-down field value after submitting the form?

I'm struggling with a dropdown field that becomes disabled once an item is selected. After submitting the form, the dropdown field loses its value and I'm left with an empty field. Any suggestions on how to keep a value in the dropdown after subm ...

Issue with Axios: XSRF token omission in headers communication

I am currently in the process of integrating a Vue JS application (Quasar framework) with an API. The API has been developed using Laravel and is utilizing sanctum for CSRF protection. Upon sending a request to the sanctum endpoint https://someweburl.com/ ...

What is the best way to display a welcoming message only once upon visiting the home page?

After gaining experience working with rails applications for a few months, I have been tasked with adding a feature that displays a welcome message to users visiting the site home page for the first time, but not on subsequent visits or page reloads. What ...

Identifying and detecting Label IDs when clicked using the for tag

I am facing an issue with labels and input fields in my code. I have multiple labels that trigger the same input field, but I want to know which specific label triggered the input field. <label id="label1" for="input1">Document1</label> <la ...

The contents of an array will be modified when the corresponding array that holds its value is altered

I have encountered a puzzling issue that I can't seem to comprehend. Specifically, I am dealing with a service array as follows: this.awesombarservice.Selected = [{id:1, value="20180101"}],[{id:1, value="20180103"}] After initializing another array ...

Sending properties to a modal form in Vue 3 using Composition API and updating the form before submitting

When receiving props from the parent component, I define the props and then assign them to a vModel for data manipulation since props are read-only. const props = defineProps<{ customer: Customer }>() model = useVModel(props, 'customer') ...

Storing Form Input in Browser's Local Memory

I am currently working on a form section where individuals can input their email addresses. However, I have encountered a couple of issues: (1) After submitting an email address, the page refreshes. While I understand that this is inevitable without usin ...

Resolving the issue of data transmission within Yii2's framework: Page-to-page data

I'm currently using Yii2-advanced-app and I have encountered an issue. I want to pass the selected value from a dropdown menu to a PHP code that displays a list with checkboxes on the same page. Here is an image for reference on what I am trying to ac ...

Reduce the number of unnecessary HTTP requests for duplicate images in VueJS applications

Scenario: On a webpage, multiple components are provided with a list of users. Following this provision, a foreach loop is utilized to call an additional component for fetching the user's image. It is plausible that various components may contain the ...

JSON nested error: Cannot read property 'length' of undefined

Having some trouble working with a nested array within a JSON in D3JS, specifically encountering a "property length undefined" error at the line: .attr("d", function(d) { return line(d.points); }). Below is the JSON data structure: [ { "aspectRatio" ...

By simply clicking a button in a React component, I aim to alter the font style of the text

function makeTextBold() { const boldText = document.querySelector('.form-control'); boldText.style.fontWeight = 'bold'; setText(boldText); } When I click the button, it redirects me to a blank page in the browser. ...

Using async/await in a for loop | The await keyword can only be used inside an asynchronous function

I've been attempting to execute the following code: async function verifyExistingUsers(db, users) { return new Promise((resolve, reject) => { var companies = [] for (const [index, user] of users.entries()) { let comp ...

Incorporating a background image into a card component using props

I attempted to add a background image to the card component through props, but the image failed to display on the card. I didn't encounter any errors, and I'm unsure what mistake I might be making. Any suggestions or alternative solutions would b ...

Utilizing the 'as' prop for polymorphism in styled-components with TypeScript

Attempting to create a Typography react component. Using the variant input prop as an index in the VariantsMap object to retrieve the corresponding HTML tag name. Utilizing the styled-components 'as' polymorphic prop to display it as the select ...

The click event that is dynamically added is triggered multiple times

On clicking a button, I am dynamically adding a row to an HTML table. The row contains a cell with a list item (li) element which has a click event assigned to it. However, when I click on the list item, the event fires multiple times and I'm unsure w ...

Performing updates on Meteor.users collection while handling a promise rejection (leveraging fcm-push with Meteor)

My current project involves the use of an NPM package called fcm-push in order to send FCM notifications to different mobile devices based on specific messages. Everything works fine when the message is successfully sent, but if the sending fails due to th ...