I am new to vue.js. I’m stuck trying to dynamically set the options of one select based on the selected value in another.
For example, I have two dropdowns named division and district.
JavaScript
x
2
1
var A = [{1: 'a'},{2:'b'}];
2
If value of A is 1, then the district select should load the related codes. I can do it with jQuery
but not with Vue.
Here is my template.
JavaScript
1
18
18
1
<div class="form-group" :class="class_obj">
2
<select name="div_code" v-model="div_code" class="form-control" required>
3
<option value="">Choose One</option>
4
<option v-for="option in div_list" v-bind:value="option.value">
5
{{ option.text }}
6
</option>
7
</select>
8
</div>
9
10
<div class="form-group" :class="class_label">
11
<label for="">District</label>
12
</div>
13
<div class="form-group" :class="class_obj">
14
<select name="dist_code" v-model="dist_code" class="form-control" required>
15
<option value="">Choose One</option>
16
</select>
17
</div>
18
Here is my javascript.
JavaScript
1
8
1
export default {
2
data():{
3
div_list: [
4
{'1': "ABC"} , {'2': "DEF"}
5
];
6
}
7
}
8
How can I load the dist_code select with related data from ajax when div_code value is 1?
Advertisement
Answer
Handle a change event on the div_code
change
JavaScript
1
11
11
1
<select name="div_code"
2
v-model="div_code"
3
@change="onDivCodeChange"
4
class="form-control"
5
required>
6
<option value="">Choose One</option>
7
<option v-for="option in div_list" v-bind:value="option.value">
8
{{ option.text }}
9
</option>
10
</select>
11
And add the onDivCodeChange
method to your Vue.
JavaScript
1
13
13
1
methods:{
2
onCodeChange(){
3
// make an ajax call and set the options for your
4
// dist_code here. For example:
5
$.ajax({
6
url: "...",
7
data: {div_code: this.div_code},
8
success: codes => this.code_list = codes
9
error: err => console.log(err)
10
})
11
}
12
}
13
And of course add code_list
as a property of your data and update your template.
JavaScript
1
5
1
<select name="dist_code" v-model="dist_code" class="form-control" required>
2
<option value="">Choose One</option>
3
<option v-for="code in code_list" :value="code.value">{{code.text}}</option>
4
</select>
5