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
class="form-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>
Main issue with your code is that you are passing static value of
trueinto yourgenderSelectedfunction. So then boolean oftruedoes not know what to do withpick.value.Instead, you can do it like this:
Just having function without parentheses will pass the
@changeevent as first argument.Or alternatively if you want to explicitly provide the event, pass
$eventinto function like so:@change="genderSelected($event)"Then your function would be reduced to:
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:
And you can skip having
genderSelectedmethod by just replacing line with@changewithv-model="gender", and then reduce your whole component down to:Here's a sandbox showing both approaches: https://stackblitz.com/edit/vue-s3erax?file=src/App.vue