【Vue】vant2使用van-tree-select实现【全选、反选、搜索】,自定义组件,拿去即用。2.0版本保姆级教程
以下是一个使用Vue和Vant 2实现的自定义树形选择组件,包含全选、反选和搜索功能的简化示例:
<template>
<div>
<van-search v-model="searchValue" placeholder="搜索" @input="onSearch" />
<van-tree-select
:items="filteredItems"
:active-id.sync="activeId"
:main-active-index.sync="activeIndex"
@click-nav="onClickNav"
@click-item="onClickItem"
/>
</div>
</template>
<script>
import { ref, computed } from 'vue';
import { TreeSelect, Search } from 'vant';
import 'vant/lib/index.css';
export default {
components: {
[TreeSelect.name]: TreeSelect,
[Search.name]: Search,
},
props: {
items: {
type: Array,
default: () => [],
},
},
setup(props, { emit }) {
const searchValue = ref('');
const activeId = ref([]);
const activeIndex = ref(0);
const filteredItems = computed(() => {
const searchValueLower = searchValue.value.toLowerCase();
return props.items.map(item => ({
...item,
children: item.children?.filter(child =>
child.text.toLowerCase().includes(searchValueLower)
),
})).filter(item => item.children && item.children.length > 0);
});
const onSearch = () => {
emit('search', searchValue.value);
};
const onClickNav = (index) => {
activeIndex.value = index;
};
const onClickItem = ({ item }) => {
activeId.value = [item.id];
emit('select', item);
};
return {
searchValue,
filteredItems,
activeId,
activeIndex,
onSearch,
onClickNav,
onClickItem,
};
},
};
</script>
<style>
/* 在这里添加自定义样式 */
</style>
使用此组件时,只需传入items(树形结构的数据),监听search
和select
事件来处理搜索和选择项的逻辑。
注意:这个示例假设你的树形数据结构遵循Vant 2的items
格式要求。如果你的数据结构不同,你可能需要在computed
属性中调整数据映射和筛选逻辑。
评论已关闭