Introduction
There might be a demand that people would like to develop dynamic select box using Vue.js.
And I was the one of them.
Then, I coded like below, and It can be also available to use old value after post from form or back.
Code
index.php
<?php
$selected_parent_category_id = '';
$selected_child_category_list = '';
if($_POST['parent_category_id']){
$selected_parent_category_id = $_POST['parent_category_id'];
}
if($_POST['child_category_id']){
$selected_child_category_id = $_POST['child_category_id'];
}
?>
<!DOCTYPE html>
<html lang="ja">
<head>
<title>Select box with Vue.js</title>
<meta charset="utf-8">
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.11"></script>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
</head>
<body>
<div id="select-category">
<form method="POST" action="./">
<select v-on:change="selectParent" v-model="value['parent']" name="parent_category_id">
<option v-for="(value, key) in parent_list" v-text="value" v-bind:value="key"></option>
</select>
<select v-model="value['child']" name="child_category_id">
<option v-for="(value, key) in child_list" v-text="value" v-bind:value="key"></option>
</select>
<input type="submit" value="SUBMIT">
</form>
</div>
<div style="display:none">
<?php if($selected_parent_category_id): ?>
<span id="selected_parent_category_id"><?php echo $selected_parent_category_id; ?></span>
<?php endif; ?>
<?php if($selected_child_category_id): ?>
<span id="selected_child_category_id"><?php echo $selected_child_category_id; ?></span>
<?php endif; ?>
</div>
</body>
<script>
var select_prefecture = new Vue ({
el : '#select-category',
data: {
value:{
'parent': $('#selected_parent_category_id').text(),
'child': $('#selected_child_category_id').text(),
},
parent_list:{
0: "選択してください",
1: "日本料理",
2: "中華料理",
3: "イタリアン"
},
child_list:{},
child_candidate_list:{
1: {
0: "選択してください",
1: "天ぷら",
2: "寿司",
3: "うどん",
},
2: {
0: "選択してください",
1: "回鍋肉",
2: "麻婆豆腐",
3: "焼売",
},
3: {
0: "選択してください",
1: "パスタ",
2: "ピザ",
3: "リゾット",
},
},
},
methods: {
selectParent() {
this.child_list = this.child_candidate_list[this.value['parent']];
},
},
mounted() {
if(this.value['parent']){
this.selectParent();
}
}
});
</script>
</html>