theme: smartblue
简介:
这个是基于 vant3.0跟vue3.0的项目,在开发中封装的一个组件
效果图:
组件功能
1. 组件的下拉框数据进行排序从小到大,分别为四个字体及以下,一行占四个位置,四个字体以上十个字体以下,一行占2个位置均匀分布,超过十个字体,一行占一个位置,本来想过说用padding自动设置数据的宽度,但是效果不太好看,最后选择了这种方法
2.防抖跟节流,这个是在搜索框加的,进行模糊查询,输入字符,结束一秒后没有任何操作在进行请求
3.进行下拉框的遍历,下拉框为一个数组,根剧数据的数据遍历下拉框,以及下拉框的隐藏跟搜索框的隐藏
开发
第一步
首先先将下拉框改造成可以进行循环渲染的
参数:
title: 菜单项标题
menuList: 父组件传来的数据
<template>
<div
class="menu-list">
<van-dropdown-menu>
<van-dropdown-item
v-for="(item,index) in menuList"
:key="item.name"
:title="self.activeName[index]||item.name"
:ref="el => { nodes[index] = el }"
>
<div>自定义内容</div>
<div class="dropdown-bottom">
<van-button
color="#F8F8F8"
type="default"
class="button"
style="color:rgba(107,107,107,1)"
@click="onfailed(index)"
>
重置
</van-button>
<van-button
type="primary"
class="button"
@click="onConfirm(index,item.data)"
>
确定
</van-button>
</div>
</van-dropdown-item>
</van-dropdown-menu>
</div>
</template>
<script>
import {
onActivated, reactive, toRefs, ref } from 'vue'
export default {
props: {
menuList: {
type: Array,
default: () => []
},
},
setup (props, ctx) {
const node = ref({
})
// 关闭的方法
const onfailed = (index) => {
// 置空title值
self.activeName[index] = ''
nodes.value[index].toggle()
ctx.emit('onfailed', index)
}
// 确定方法
const onConfirm = (index, item) => {
if (self.menuValue[index] !== '') {
const id = self.menuValue[index]
// 确定以后修改title值
self.activeName[index] = item[self.menuValue[index]].name
// 数组的下标以及数据的下标
const obj = {
index,
id
}
nodes.value[index].toggle()
ctx.emit('menuChange', obj)
}
}
return {
...toRefs(self),
nodes,
onfailed,
onSelect,
onConfirm,
gridList
}
}
}
</script>
第二步
添加搜索框以及搜索框的防抖节流方法
封装防抖节流
//common.js
// 节流函数
export function throttle (fn, wait) {
// previous是上一次执行fn的时间,timer是定时器
let previous = 0
let timer = null
// 将throttle处理结果当作函数返回
return function (...args) {
// 获取当前时间戳
let now = +new Date()
// 判断上次触发的时间和本次触发的时间差是否小于时间间隔
if (now - previous < wait) {
// 如果小于,则为本次触发操作设定一个新的定时器,定时器时间结束后执行函数fn
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
previous = now
fn.apply(this, args)
}, wait)
} else {
// 第一次执行或者时间间隔超出了设定的时间间隔,执行函数fn
previous = now
fn