I have two form fields: country and region. First, you have to choose a country than a region. If a country is selected I add the regions (options) to the next component: Region
.
I add the options for the regions with axios.
The scenario where I have an issue: when the user chooses a country then a region then gets back to change country.
The region needs to be reset. I tried to do that with the lifecycle hooks mounted
and created
but VeeValidate
detects no changes. So the value is properly changed but VeeValidate
does not detects it. I solved it with adding watch
(with nextTick
) inside mounted
but I doubt it that this is a good solution. Does anyone have any other idea?
I have little experience with Vue.js. Any help is appreciated.
This my full SelectBox.vue
:
<template>
<div>
<v-select
@input="setSelected"
:options="choices"
:filterable="filterable"
:value="value"
:placeholder="placeholder"
></v-select>
</div>
</template>
<script>
import vSelect from "vue-select";
import debounce from 'lodash/debounce';
import axios from 'axios';
//axios.defaults.headers.get["Vuejs"] = 1;
export default {
props: [
"options", "filterable",
"value", "url",
"name", "placeholder"
],
data: function () {
var choices = this.options;
if (this.name == "region") {
choices = this.$store.state["regionChoices"] || [];
if (this.value && !choices.includes(this.value)) {
this.toReset = true;
}
if ( Array.isArray(choices) && choices.length < 1) {
this.addError("region", "Country is not selected or there are not available options for your selected country.");
}
}
return {
choices: choices
// refPrefix: this.name + "Ref"
}
},
components:{
vSelect
},
inject: ["addError"],
methods: {
searchRegions: debounce((val, vm) => {
axios.get(vm.url + val)
.then(res => {
vm.$store.state["regionChoices"] = res.data.results;
});
}, 250),
setSelected(val) {
this.$emit("input", val);
if (this.name == "country") {
const countryId = val ? val.value : "0";
this.searchRegions(countryId, this);
}
},
},
mounted() {
if (this.name == "region") {
this.$watch('value', function(value) {
if (this.toReset) {
this.$nextTick(function () {
this.setSelected("");
this.toReset = value ? true : false;
});
}
}, { immediate: true });
}
},
}
</script>