Vue3搭配Element Plus 实现候选搜索框效果

Vue3搭配Element Plus 实现候选搜索框效果_第1张图片

直接上代码

    
        
        
        
        
        
//selectedCity这个是选中候选框数据的处理方法

{{ item.label }}

 input="inputChange" @focus="inputFocusFn" @blur="inputBlurFn" placeholder="请输入项目名称" clearable>

Vue3搭配Element Plus 实现候选搜索框效果_第2张图片

解释一下 在值改变时 将数据进行过滤 失去焦点隐藏候选框 获取焦点将完整数据渲染到候选框中

// 搜索框数据
const projectName = ref(null)

//控制候选框显示隐藏
const isShow = ref(false)

// 渲染到候选框的数据
const cityArr = ref(null)

// 搜索框Change事件
const inputChange = () => { 
        //搜索框值为空 候选框关闭
    if (projectName.value == '') {
        isShow.value = false
    } else {
          //输入框输入的时候 遍历总数据 将过滤出来的数据放入其中
        if (cityOptions.value.length > 0) { 
            cityArr.value = []
            cityOptions.value.forEach((item, index, array) => {
                if (item.label.indexOf(projectName.value) >= 0) { 
                    cityArr.value.push(item)
                }
            })
            // cityOptions.value = cityArr
        }
        isShow.value = true
        // getTreeListFn()
    }
}
// 搜索框聚焦事件 请求跟下面获取总数据请求一样 不要问我为什么不直接调用下面的方法 因为我这个是项目里方法 好多数据我都删除了 下面的请求里面有好多逻辑处理 不好直接调用 我就又书写了一遍
const inputFocusFn = () => { 
    isShow.value = true
        let params = {
        name: projectName.value
    }
    getTreeList(params).then(res => {
        if (res.code == 200) {
             cityArr.value = res.data
        }
    })
    //   getTreeListFn()
}
// 搜搜框失焦事件
const inputBlurFn = () => { 
     isShow.value = false
}

// 获取总的项目树数据
function getTreeListFn() { 
    let params = {
        name: projectName.value
    }
    getTreeList(params).then(res => { 
        if (res.code == 200) { 
               //候选框总数据
            cityOptions.value = res.data
        }
    })
}
//selectedCity这个是选中候选框数据的处理方法 
const selectedCity = (id) => { 
    //处理逻辑
 }

你可能感兴趣的:(Element-Plus,小tips,vue.js,前端,javascript)