赞
踩
先上效果图:
基于Ant Design的树结构,vue3
- <template>
- <div>
- <a-input-search
- v-model:value="searchValue"
- style="margin-bottom: 8px"
- placeholder="Search"
- />
- <a-tree
- :expandedKeys="expandedKeys"
- :auto-expand-parent="autoExpandParent"
- :tree-data="gData"
- @expand="onExpand"
- >
- <template #title="{ title }">
- <span v-if="title.indexOf(searchValue) > -1">
- {{ title.substr(0, title.indexOf(searchValue)) }}
- <span style="color: #f50">{{ searchValue }}</span>
- {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
- </span>
- <span v-else>{{ title }}</span>
- </template>
- </a-tree>
- </div>
- </template>
- <script>
- import { defineComponent, ref, watch } from "vue";
- const genData = [
- {
- title: "河北省",
- key: "河北省",
- children: [
- {
- title: "石家庄市",
- key: "石家庄市",
- children: [
- {
- title: "桥西区",
- key: "桥西区",
- },
- {
- title: "新华区",
- key: "新华区",
- },
- ],
- },
- {
- title: "唐山市",
- key: "唐山市",
- children: [
- {
- title: "丰南区",
- key: "丰南区",
- },
- ],
- },
- ],
- },
- {
- title: "山西省",
- key: "山西省",
- children: [
- {
- title: "太原市",
- key: "太原市",
- },
- {
- title: "大同市",
- key: "大同市",
- children: [
- {
- title: "云冈区",
- key: "云冈区",
- },
- {
- title: "新荣区",
- key: "新荣区",
- },
- ],
- },
- ],
- },
- ];
-
- const dataList = [];
-
- const generateList = (data) => {
- for (let i = 0; i < data.length; i++) {
- const node = data[i];
- const key = node.key;
- dataList.push({
- key,
- title: key,
- });
-
- if (node.children) {
- generateList(node.children);
- }
- }
- };
-
- generateList(genData);
-
- const getParentKey = (key, tree) => {
- let parentKey;
-
- for (let i = 0; i < tree.length; i++) {
- const node = tree[i];
-
- if (node.children) {
- if (node.children.some((item) => item.key === key)) {
- parentKey = node.key;
- } else if (getParentKey(key, node.children)) {
- parentKey = getParentKey(key, node.children);
- }
- }
- }
-
- return parentKey;
- };
-
- export default defineComponent({
- setup() {
- const expandedKeys = ref([]);
- const searchValue = ref("");
- const autoExpandParent = ref(true);
- const gData = ref(genData);
-
- const onExpand = (keys) => {
- expandedKeys.value = keys;
- autoExpandParent.value = false;
- };
-
- watch(searchValue, (value) => {
- const expanded = dataList
- .map((item) => {
- if (item.title.indexOf(value) > -1) {
- return getParentKey(item.key, gData.value);
- }
-
- return null;
- })
- .filter((item, i, self) => item && self.indexOf(item) === i);
- expandedKeys.value = expanded;
- searchValue.value = value;
- autoExpandParent.value = true;
- });
- return {
- expandedKeys,
- searchValue,
- autoExpandParent,
- gData,
- onExpand,
- };
- },
- });
- </script>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。