vue.jsvue-clivee-validatevue-select

Update initial value. Vee validate does not detect changes?


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>

Solution

  • My Vue model was defined in the parent component. So my model property also has to be updated from the parent of my component. I added the method resetRegion to my parent component. And so I can use it in my child component with provide and inject.

    My code snippet of the parent component:

    export default {
        name: "form-template",
        components: {
            FieldGroup,
        },
        provide() {
            return {
                addError: this.addError,
                resetRegion: this.resetRegion
            }
        },
        methods: {
            ...mapMutations({
                updateField: "applicant/updateField"
            }),
            addError(field, msg) {
                this.errors.add({field: field, msg: msg});
            },
            resetRegion() {
                this.formData.region = "";
            }
        }
    }
    

    My code snippet of the child component:

    export default {
        props: [
            "options", "value", "multiple",
            "name", "placeholder", "url"
        ],
        components:{
            vSelect
        },
        inject: ["addError", "resetRegion"],
        computed: {
            choices: function () {
                let choices = this.options;
                if (this.name == "region") {
                    choices = this.$store.state["regionChoices"];
                }
                return choices || []
            }
        },
        methods: {
            searchRegions(val, vm) {
                vm.$store.state["regionChoices"] = [];
                axios.get(vm.url + "?pk=" + val)
                .then(res => {
                    const choices = res.data.results || [];
                    vm.$store.state["regionChoices"] = choices;
                    if (Array.isArray(choices)) {
                        const curValue = vm.$store.state.lead.formData.region;
                        if (choices.length < 1 || (curValue && !choices.some(e => e.id === curValue))) {
                            this.resetRegion();
                        }
                    } else {
                        this.resetRegion();
                    }
                });
            },
            setSelected(val) {
                this.$emit("input", val);
                if (this.name == "country") {
                    this.searchRegions(val, this);
                }
            }
        },
        mounted() {
            if (this.name == "region") {
                if(!Array.isArray(this.choices) || this.choices.length < 1) {
                    this.addError("region", window.HNJLib.localeTrans.regionErr);
                }
            }
        },
        created() {
            if (this.name == "country" && this.value && !this.$store.state.hasOwnProperty("regionChoices")) {
                this.searchRegions(this.value, this);
            }
        }
    }
    

    So my problem was solved.