Just starting out with Vue and I need to develop a tiered select field form. This means that the option selected in A will determine the options for B, which in turn determines the options for C.
I'm still learning frontend frameworks so this might not be the best design approach. However, not every instance of A (SelectState.vue
) in a view requires all the children, so I wanted to make them modular.
Currently, I have a top-level component displaying the select options:
SelectState.vue
<template>
<div id="select-state">
<span>{{ label }}</span>
<select v-model="selectedState">
<option v-for="state in states" :key="state">
{{ state }}
</option>
</select>
</div>
</template>
<script>
export default {
name: 'select-state',
data() {
return {
selectedState: '',
states: ['TX']
};
},
props: ['label']
// this.states = axios.get('xxx')
}
</script>
Index.vue
<template>
<div id="form">
<v-select-state label="State"></v-select-state>
<v-select-zip label="Zip"></v-select-zip>
</div>
</template>
<script>
import SelectState from './SelectState.vue'
import SelectZip from './SelectZip.vue'
export default {
name: 'Index',
components: {
'v-select-state': SelectState,
'v-select-Zip': SelectZip
}
}
</script>
Then, I have a SelectZip.vue
which is similar to SelectState.vue
, except it requires a parameter in its
axios.get('XXX', params = {'state': ???})
. But I'm struggling to figure out how to pass that necessary parameter.
Thank you in advance!
Edit: Combined with @dziraf's answer, my working albeit lengthy SelectedZip.vue
looks like this:
<template>
<div id="select_zip">
<span>{{ label }}</span>
<select v-model="selected_zip">
<option v-for="zip in zips" :key="zip">
{{ zip }}
</option>
</select>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'select_zip',
data() {
return {
zips: []
};
},
props: ['label'],
computed: {
selected_zip: {
get () { return this.$store.state.formModule.zip },
set (value) { this.$store.commit('formModule/setZips', value) }
},
selected_state: {
get () { return this.$store.state.formModule.state }
}
},
methods: {
getValidZips(state) {
axios.post('/api/v1/get_valid_zips', {
params:{'state': state }})
.then(response => {
this.zips = response.data
})
.catch(error => {
console.log(error)
})
}
},
watch: {
selected_state(value) {
this.getValidZips(value)
}
}
}
</script>