Vue中select預設選中下拉選項第一條(舉例iview AutoComplete元件)
阿新 • • 發佈:2020-12-31
技術標籤:vuevueselectautocompleteiview
一、html中
- 靜態
給對應option元素直接新增selected屬性<select> <option value="0">one</option> <option value="1">two</option> <option value="2" selected>three</option> </select>
- 動態
option載入完成後給對應元素新增selected屬性$
二、vue中
- 選中第一項同時並改變select繫結的value(正常業務)
<template> <select v-model="value"> <option value="0">New York</option> <option value="1">London</option> <option value=
- 可模糊匹配,select輸入模糊匹配,預設選中下拉選項中第一項,但select繫結的value不變,即下圖所示:
我的做法是:-
輸入值改變時,監聽change事件引起下拉選項的發生改變
-
判斷篩選後的下拉選項Dom元素中沒有選中項,為第一項New York新增選中樣式;若有選中項則不操作
-
監聽回車事件,如此時有回車事件,判斷下拉選項Dom中第一項有選中樣式則將value的值變更為選項中第一項的值,即this.value = ‘New York’,並將下拉選項框隱藏
-
我的實際列子是使用iviewUI中的AutoComplete元件做的(簡單舉個例子,只提供參考)
<template> <div id="search-input-component"> <AutoComplete v-model="value" type="text" @keydown.enter.native.prevent="enterEvent" @on-change="change" > <Option v-for="item in changeList" :value="item.value" :key="item.value" > {{item.name}} </Option> </AutoComplete> </div> </template> <script> export default { data () { return { value: '', // AutoComplete繫結的值 valueLists: [ // { value: '選項值', name: '選項名' } ], // 全部拉選項列表 changeList: [] // 實時模糊匹配的下拉選項列表 } }, created () { this.getAllList() }, methods: { // 獲取所有下拉選項 getAllList () { // ...Data this.valueLists = Data this.changeList = Data }, // 輸入change事件 change (val) { // 模糊匹配邏輯,重新生成下拉選項列表 this.changeList = [] this.valueLists.map(item => { if (item.toUpperCase().indexOf(val.toUpperCase()) !== -1) { this.changeList.push(item) } }) this.$nextTick(() => { // 下拉框中所有選項的Dom const ele = document.querySelectorAll('#search-input-component .ivu-select-dropdown.ivu-auto-complete .ivu-select-dropdown-list .ivu-select-item') let hasFocus = false // 初始賦值沒有選中項 for(let i=0; i < ele.length; i++) { // 判斷有選中項 if (ele[i].className.indexOf('ivu-select-item-focus') > -1) { hasFocus = true break } } // 判斷沒有選中項,則選中第一項(新增選中樣式) if (!hasFocus && (ele[0].className.indexOf('ivu-select-item-focus') === -1)) { ele[0].classList += ' ivu-select-item-focus' } }) }, // 回車事件 enterEvent (card, isUpdate) { const selectDom = document.querySelector('#search-input-component .ivu-select-dropdown.ivu-auto-complete') // 下拉選項有匹配到資料 並且 下拉選項沒有隱藏 if (this.changeList.length && !selectDom.style.display) { // 下拉框中所有選項的Dom const items = document.querySelectorAll('#search-input-component .ivu-select-dropdown.ivu-auto-complete .ivu-select-dropdown-list .ivu-select-item') let hasFocus = false // 初始賦值沒有選中項 for(let i=0; i < items.length; i++) { // 判斷有選中項 if (items[i].className.indexOf('ivu-select-item-focus') > -1) { hasFocus = true break } } // 判斷沒有選中項,則選中第一項 if (!hasFocus) { this.value = this.changeList[0].cardId } selectDom.style.display = 'none' // 隱藏下拉框 } } } } </script>
-