2017-09-23 70 views
1

我剛開始使用Vue,(這看起來非常好),我遇到了問題。Vue在助推器下拉菜單上選擇樣式功能

我有一個bootstrap4下拉菜單,我用它來填充隱藏窗體(單擊下拉菜單項將數據值保存到下面的窗體中)。

這只是因爲我不能設計正常的選擇/選項下拉菜單,因爲我願意。

這一切工作正常,直到我嘗試實施vue,因爲我不直接使用選擇組件,vue select documentation提供的解決方案似乎不工作。

任何幫助將不勝感激。

在此先感謝


HTML

<div class="dropdown"> 
    <button class="btn btn-secondary dropdown-toggle device-dropdown" type="button" data-toggle="dropdown" aria-haspopup="true" 
     aria-expanded="false"> 
     All Devices 
    </button> 
    <div class="dropdown-menu" aria-labelledby="device-dropdown"> 
     <a class="dropdown-item" href="#" data-value="all">All Devices</a> 
     <a class="dropdown-item" href="#" data-value="imac">iMac</a> 
     <a class="dropdown-item" href="#" data-value="macbook">MacBook</a> 
     <a class="dropdown-item" href="#" data-value="ipad">iPad</a> 
     <a class="dropdown-item" href="#" data-value="iphone">iPhone</a> 
    </div> 

    <select name="device" class="hidden-device-dropdown"> 
     <option></option> 
    </select> 
</div> 

JS

// copies the selected dropdown element into a hidden select in the form 
$('.dropdown-menu').click(function (e) { 
    e.preventDefault(); 
    // change button text to selected item 
    var selected = $(e.target); 
    $(".device-dropdown").text($(selected).text()); 

    // change option value (inside select) to selected dropdown 
    var form = $("select.hidden-device-dropdown").children("option"); 
    $(form).val(selected.data("value")); 
}); 

編輯:看起來像v-on:click="device = '...'"可能會讓我的功能,我後,這是一個很好的方式呢?似乎是複製了很多代碼

+0

這是關於解決問題的最佳方法,而不是一個特定的代碼示例:) – Ollie

回答

1

我會建議一個組件。

Vue.component("bs-dropdown",{ 
    props:["options", "value"], 
    template:` 
    <div class="dropdown"> 
    <button class="btn btn-secondary dropdown-toggle" 
      :class="id" 
      ref="dropdown" 
      type="button" 
      data-toggle="dropdown" 
      aria-haspopup="true" 
      aria-expanded="false"> 
     {{selected.text}} 
    </button> 
    <div class="dropdown-menu" :aria-labelledby="id"> 
     <a class="dropdown-item" 
     href="#" 
     v-for="option in options" 
     @click="selected = option"> 
     {{option.text}} 
     </a> 
    </div> 
    </div> 
    `, 
    computed:{ 
    selected:{ 
     get() {return this.value}, 
     set(v){this.$emit("input", v)} 
    }, 
    id(){ 
     return `dropdown-${this._uid}` 
    } 
    }, 
    mounted(){ 
    $(this.$refs.dropdown).dropdown() 
    } 
}) 

該組件包裝引導程序功能,這是您在與外部庫集成時通常要執行的操作。

使用它,像這樣:

<bs-dropdown :options="devices" v-model="selected"></bs-dropdown> 

這裏是一個codepen demonstrating它在行動。

如果/當您需要該值而不是將其複製到隱藏的選擇中時,該值是一個與v-model綁定的數據屬性。無論你喜歡,你都可以使用它。

+0

這正是我之後的事情:)謝謝。很高興看到它背後的方法 – Ollie