Home > Software design >  how to use dropdown box to filter the display/hide div element in vue js
how to use dropdown box to filter the display/hide div element in vue js

Time:11-06

I am new to VueJS and trying to create a simple dropdown box to filter the display/hide of div but encounter some problems.

<template>
  <select
    
    aria-label="Default select example"
    name="filter"
    @change="genderSelected(true)"
  >
    <option value="Male">Male</option>
    <option value="Female">Female</option>
  </select>
</template>

Control display/hide of the div:

<div v-if="gender === 'Male'">Male</div>

<div v-if="gender === 'Female'">Female</div>

Vue

<script>
import { ref, onMounted } from "vue";

export default {
  setup() {
    const gender = ref("Male");
    const genderSelected = (pick) => {
      if (pick.value === "Male") {
        gender.value = "Male";
      } else if (pick.value == "Female") {
        gender.value = "Female";
      }
    };
    return {
      genderSelected,
      gender,
    };
  },
};
</script>

CodePudding user response:

Main issue with your code is that you are passing static value of true into your genderSelected function. So then boolean of true does not know what to do with pick.value.

Instead, you can do it like this:


    <select
      
      aria-label="Default select example"
      name="filter"
      @change="genderSelected" >
      <option value="Male">Male</option>
      <option value="Female">Female</option>
    </select>

Just having function without parentheses will pass the @change event as first argument.

Or alternatively if you want to explicitly provide the event, pass $event into function like so: @change="genderSelected($event)"

Then your function would be reduced to:

const genderSelected = (event) => { gender.value = event.target.value; };

That should get you working code.

As a bonus, you can trim your template a little bit by using this, which is equivalent of your sample code:

<div>{{ gender }}</div>

And you can skip having genderSelected method by just replacing line with @change with v-model="gender", and then reduce your whole component down to:

<template>
  <div id="app">
    <div>{{ gender }}</div>
    <select
      
      aria-label="Default select example"
      name="filter"
      v-model="gender"
    >
      <option value="Male">Male</option>
      <option value="Female">Female</option>
    </select>
  </div>
</template>

<script>
import { ref } from 'vue';

export default {
  name: 'App',
  setup() {
    const gender = ref('Male');
    return {
      gender,
    };
  },
};
</script>

Here's a sandbox showing both approaches: https://stackblitz.com/edit/vue-s3erax?file=src/App.vue

  • Related