> ## Content Index
> Fetch the complete content index at: https://blog.anthea.day/llms.txt
> Use this file to discover other available public pages before exploring further.

# bootstrap-select 應用 (2)：連動應用與關鍵字搜尋
- URL: https://blog.anthea.day/series-bootstrap-select-2/
- Published: 2022-08-14T09:48:21.000Z
- Updated: 2026-10-21T04:07:59.000Z
- Author: Anthea / 芫荽
- Tags: #Migrated-1792241843742, #Import 2026-10-17 12:57, Coding, Bootstrap, bootstrap-select 應用

上一篇提到基本的下拉式選單應用之後，接下來要記錄的是多個選單彼此連動時的應用。

以前一篇工作上的例子來說，通常把資料用縣市、鄉鎮市區、地段這三種層級區分開來，所以當我選到台北市的時候，鄉鎮市區的選單裡就不應該會出現西屯區的項目，這個就是我所謂的**連動** — — 當其中一個選項的值改變，就會讓其他的選單內容也跟著不同。

#### 簡單的 API 準備

清單來源一樣是[地籍圖資網路便民服務系統](https://easymap.land.moi.gov.tw/Home?ref=blog.anthea.day)，我只整理了台中市的西屯區和西區這兩個行政區底下的段名作為範例。

```C#
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace bootstrap_selected_sample.Controllers;

[ApiController]
[Route("api/[controller]")]
public class CodeController : ControllerBase
{
    [HttpGet]
    public IActionResult Counties()
    {
        var path = "files/county.json";
        var json = ReadFromJson(path);
        var info = JsonConvert.DeserializeObject<List<SimpleInfo>>(json);
        return Ok(info);
    }

    [HttpGet("{county}")]
    public IActionResult Towns(string county)
    {
        var path = county.ToUpper() switch
        {
            "B" => "files/taichung.json"
        };
        var json = ReadFromJson(path);
        var info = JsonConvert.DeserializeObject<List<SimpleInfo>>(json);
        return Ok(info);
    }

    [HttpGet("{county}/{town}")]
    public IActionResult Sections(string county, string town)
    {
        var path = "";
        switch (county)
        {
            case "B" when town == "06":
                path = "files/xitun.json";
                break;
            case "B" when town == "04":
                path = "files/xi.json";
                break;
        }
        
        var json = ReadFromJson(path);
        var info = JsonConvert.DeserializeObject<List<ComplexInfo>>(json);
        return Ok(info);
    }

    private string ReadFromJson(string path)
    {
        var reader = new StreamReader(path);
        var readToEnd = reader.ReadToEnd().Replace("\r", "").Replace("\n", "").Replace(" ", "");
        return readToEnd;
    }
}

public class SimpleInfo
{
    public string Id { get; set; }
    public string Name { get; set; }
}

public class ComplexInfo : SimpleInfo
{
    public string OfficeCode { get; set; }
}
```

---

### 使用 bootstrap-select 進行連動

首先，我們依照上次的方法，使用 `Vue.$nextTick()` 來試試看效果怎麼樣吧。

```html
<div id="app" class="container my-5">
    <div class="row">
        <div class="col-12 mt-5 row">
            <form>
                <div class="row g-3 align-items-center">
                    <div class="col-auto">
                        <label for="county-select" class="col-form-label">縣市</label>
                    </div>
                    <div class="col-auto">
                        <select id="county-select" v-model="selected.county">
                            <option v-for="c in code.county" :value="c">{{c.name}}</option>
                        </select>
                    </div>
                    <div class="col-auto">
                        <label for="county-select" class="col-form-label">鄉鎮市區</label>
                    </div>
                    <div class="col-auto">
                        <select id="town-select" v-model="selected.town">
                            <option v-for="t in code.town" :value="t">{{t.name}}</option>
                        </select>
                    </div>
                    <div class="col-auto">
                        <label for="county-select" class="col-form-label">地段</label>
                    </div>
                    <div class="col-auto">
                        <select id="section-select" v-model="selected.section">
                            <option v-for="s in code.section" :value="s">{{s.name}}</option>
                        </select>
                    </div>
                </div>
            </form>
        </div>
        <div class="col-12 mt-3 row">
            <div class="col-4" v-if="selected.county !== null && selected.town !== null && selected.section !== null">
                已經選擇：{{selected.county.name}} {{selected.town.name}} {{selected.section.name}}
            </div>
        </div>
    </div>
</div>
```

```js
const app = Vue.createApp({
    data(){
        return{
            code:{
                county: [],
                town: [],
                section: []
            },
            selected:{
                county: null,
                town: null,
                section: null
            }
        }
    },
    methods:{
        getCounties(){
            this.selected.county = null;
            this.selected.town = null;
            this.selected.section = null;
            axios({
                method: 'get',
                url: './api/code'
            }).then(res => {
                this.code.county = res.data;
                Vue.nextTick(() => {
                    $('#county-select').selectpicker();
                })
            })
        },
        getTowns(){
            this.selected.town = null;
            this.selected.section = null;
            axios({
                method: 'get',
                url: `./api/code/${this.selected.county.id}`
            }).then(res => {
                this.code.town = res.data;
                Vue.nextTick(() => {
                    $('#town-select').selectpicker();
                })
            })
        },
        getSections(){
            this.selected.section = null;
            axios({
                method: 'get',
                url: `./api/code/${this.selected.county.id}/${this.selected.town.id}`
            }).then(res => {
                this.code.section = res.data;
                Vue.nextTick(() => {
                    $('#section-select').selectpicker();
                })
            })
        },
    },
    watch:{
        'selected.county': function (newVal) {
            if (newVal === '' || newVal === null) return;
            this.getTowns();
        },
        'selected.town': function (newVal) {
            if (newVal === '' || newVal === null) return;
            console.log(newVal);
            this.getSections();
        },
    },
    mounted(){
        this.getCounties();
    }
});
app.mount('#app');
```

![](https://cdn-images-1.medium.com/max/800/1*Ych5OjvH4kJfjIyHDFFE6w.gif)

執行之後你應該可以發現兩個問題：還沒有初始化過的選單會長的很醜，以及，我明明資料內容更新了，但為甚麼畫面上仍然是舊的資料呢？我的資料又去哪裡了 😠

在官方文件 Methods 的頁面中，可以看到有一個叫做 `refresh` 的方法，這個方法可以讓我們更新畫面上的 UI 呈現：

![](https://cdn-images-1.medium.com/max/800/1*pC5WVlNwixU5WdKpRncJtw.png)

#### 使用 refresh 修正

既然官方都提供了這個用法，那我們就依照建議修改一下程式碼吧：

```js
const app = Vue.createApp({
    data(){...},
    methods:{
        getCounties(){
            axios({
                method: 'get',
                url: './api/code'
            }).then(res => {
                this.code.county = res.data;
                
                // 記得要包在 Vue.nextTick() 中才有效喔
                Vue.nextTick(() => {
                    $('#county-select').selectpicker('refresh');     // 更新 county
                    $('#town-select').selectpicker('refresh');       // 更新 town
                    $('#section-select').selectpicker('refresh');    // 更新 section
                })
            })
        },
        getTowns(){...     // 更新 town 和 section },
        getSections(){...  // 更新 section },
    },
    watch:{...},
    mounted(){
        this.getCounties();
        
        // 一次全部初始化
        Vue.nextTick(() => {
            $('select').selectpicker();
        })
    }
});
app.mount('#app');
```

![](https://cdn-images-1.medium.com/max/800/1*45MblkchAknkTM0Tfd6qrQ.gif)

資料看起來有被正確的更新到 UI 上了 ㊗️ 但為甚麼我的清單看起來還是怪怪的咧 😵 其實，在官方的完整範例中，是先找到要刪除的選項，移除之後才進行 refresh，但不曉得為甚麼，就算按照官方的範例我也無法正常移除 😵

![](https://cdn-images-1.medium.com/max/800/1*kexTZLi880coL1Yj_u_SPQ.png)

官方文件上關於 refresh 的使用範例

#### 使用 destroy 修正

所以最後我採用的方法，是直接把整個元件 `destroy` 掉，更新資料的時候再重新建立一個。

將 Vue.nextTick() 中的內容修改成仙 dsetroy 再重建

![](https://cdn-images-1.medium.com/max/800/1*0z3g40BAUQDIv6lGWLar9Q.gif)

可以看到正確的資料有被好好地呈現在 UI 上了 🎊

---

#### 參考文章

- [bootstrap-select 官方文件](https://developer.snapappointments.com/bootstrap-select/examples/?ref=blog.anthea.day)