Xin's blog Xin's blog
首页
  • 前端文章

    • HTML
    • CSS
    • JavaScript
    • Vue
    • 组件与插件
    • CSS扩展语言
  • 学习笔记

    • 《JavaScript教程》笔记
    • 《JavaScript高级程序设计》笔记
    • 《ES6 教程》笔记
    • 《Vue》笔记
    • 《TypeScript 从零实现 axios》
    • 《Git》学习笔记
    • TypeScript笔记
    • JS设计模式总结笔记
  • 前端框架面试题汇总
  • 基本面试题
  • 进阶面试题
  • 其它
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 前后端联调
  • mock.js
  • 奇技淫巧
  • 分类
  • 标签
  • 归档
关于
GitHub (opens new window)

Xin

英雄可不能临阵脱逃啊~
首页
  • 前端文章

    • HTML
    • CSS
    • JavaScript
    • Vue
    • 组件与插件
    • CSS扩展语言
  • 学习笔记

    • 《JavaScript教程》笔记
    • 《JavaScript高级程序设计》笔记
    • 《ES6 教程》笔记
    • 《Vue》笔记
    • 《TypeScript 从零实现 axios》
    • 《Git》学习笔记
    • TypeScript笔记
    • JS设计模式总结笔记
  • 前端框架面试题汇总
  • 基本面试题
  • 进阶面试题
  • 其它
  • 技术文档
  • GitHub技巧
  • Nodejs
  • 博客搭建
  • 前后端联调
  • mock.js
  • 奇技淫巧
  • 分类
  • 标签
  • 归档
关于
GitHub (opens new window)
  • HTML

  • CSS

  • JavaScript

  • Vue

    • 知识点

    • 方法

      • 使用el-select,出现切换数据后item消失的问题
      • 实现一个二级item的下拉框
        • 效果
        • html代码
        • js代码
        • 样式
        • 数据结构
      • 给按钮加上权限校验后导致v-if失效的问题
      • vue的权限管理
    • vue API

  • 组件与插件

  • css扩展语言

  • 学习笔记

  • 前端
  • Vue
  • 方法
ctrlwin
2021-11-17

实现一个二级item的下拉框

# 实现一个二级item的下拉框

# 效果

由于时间比较紧促,所有代码写的略显臃肿,以后有时间再优化优化。

这里补充一下,一级和二级的数据是分开的,也就是点击一级菜单才会去拿二级菜单的数据 别问为啥要这么设计,问就是需求🤡

二级类目下拉框

# html代码

<template>
  <div
    v-clickoutside="handleClose"
    class="dropDown-container"
  >
    <div
      ref="dropInputBox"
      class="select-input"
      :class="{ isError: validError }"
      :style="{ width: width + 'px' }"
      @click.stop="activeDrop"
    >
      <div
        v-if="multiple"
        class="select_content"
        :class="{ scroll: positionTop >= 66 && multiple }"
        :style="{ width: width + 'px' }"
      >
        <span>
          <span
            v-for="(item, index) in selectMutipleName"
            :key="item.code"
            class="el-tag el-tag--info"
          >{{ item.name }}
            <i
              class="el-tag__close el-icon-close"
              @click="deleteItem(index)"
            />
          </span>
        </span>
        <input
          v-if="selectMutipleName.length <= 0"
          v-model="selectName"
          class="select-input__inner"
          type="input"
          readonly="readonly"
          autocomplete="off"
          :placeholder="placeholder"
          :style="{ width: width + 'px' }"
        >
      </div>
      <input
        v-else
        v-model="selectName"
        class="select-input__inner"
        type="input"
        readonly="readonly"
        autocomplete="off"
        :placeholder="placeholder"
        :style="{ width: width + 'px' }"
      >
      <span class="select-icon">
        <i
          class="icon el-icon-arrow-up"
          :class="{ selectReverse: isShowSelect }"
        />
      </span>
    </div>
    <div
      ref="dropListBox"
      class="selectList-box"
      :class="{ selectActive: isShowSelect }"
      :style="{ top: positionTop + 'px' }"
    >
      <div class="selectList-wrap">
        <ul class="select-list">
          <li
            v-for="(item, index) in dataList"
            :key="item.code"
            class="select-list-item"
            :class="{
              hasChild: childList,
              selected: isSelected(item, 'parent'),
            }"
            @click.stop="selectItems(item)"
          >
            <span
              @mouseenter="selectItemEnter(false, index)"
              @mouseleave="selectItemLeave(false)"
            >
              {{ item.name }}</span>
            <div
              class="select-label"
              :class="{ onHover: activeIndex == index && onHover }"
            />
            <ul
              v-if="
                childList.length > 0 &&
                  currentItem &&
                  item.code == currentItem.code
              "
              class="select-list child-list"
            >
              <li
                v-for="(ite, ind) in childList"
                :key="ite.code"
                class="select-list-item child-list-item"
                :class="{ selected: isSelected(ite, 'child') }"
                @click.stop="selectItems(item, ite)"
              >
                <span
                  @mouseenter="selectItemEnter(true, index, ind)"
                  @mouseleave="selectItemLeave(true)"
                >{{ ite.name }}</span>
                <div
                  class="select-child-label"
                  :class="{
                    onHover:
                      activeIndex == index &&
                      activeChildIndex == ind &&
                      onChildHover,
                  }"
                />
              </li>
            </ul>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121

# js代码

<script>
const clickoutside = {
  // 初始化指令
  bind(el, binding) {
    function documentHandler(e) {
      // 这里判断点击的元素是否是本身,是本身,则返回
      if (el.contains(e.target)) {
        return false;
      }
      // 判断指令中是否绑定了函数
      if (binding.expression) {
        // 如果绑定了函数 则调用那个函数,此处binding.value就是handleClose方法
        binding.value(e);
      }
    }
    // 给当前元素绑定个私有变量,方便在unbind中可以解除事件监听
    el.__vueClickOutside__ = documentHandler;
    document.addEventListener("click", documentHandler);
  },
  update() {},
  unbind(el) {
    // 解除事件监听
    document.removeEventListener("click", el.__vueClickOutside__);
    delete el.__vueClickOutside__;
  },
};
import { querySubCategories } from "@api/microPurchasingZone";
export default {
  name: "DropDown",
  directives: { clickoutside },
  model: {
    prop: "value",
    event: "change",
  },
  props: {
    value: {
      type: [Object, String, Array],
      default: () => {},
    },
    isEdit: {
      type: Boolean,
      default: () => false,
    },
    validError: {
      type: Boolean,
      default: () => false,
    },
    placeholder: {
      type: String,
      default: () => "请选择",
    },
    createType: {
      type: String,
      default: () => "",
    },
    multiple: {
      type: Boolean,
      default: false,
    },
    width: {
      type: [Number, String],
      default: 336,
    },
  },
  data() {
    return {
      isShowSelect: false,
      selectName: "",
      selectModel: null,
      onHover: false,
      onChildHover: false,
      activeIndex: -1,
      activeChildIndex: -1,
      selectParent: null,
      selectChild: null,
      dataList: [],
      childList: [],
      selectMutipleName: [],
      currentItem: null,
      currentIndex: -1,
      positionTop: 36,
    };
  },
  watch: {
    value(val) {
      if (this.isEdit) {
        this.selectModel = val;
        this.setEditData();
      }
      if (!val || JSON.stringify(val) == "{}") {
        this.selectName = null;
        this.selectParent = null;
        this.selectChild = null;
        this.currentItem = null;
        this.selectMutipleName = [];
        if (this.multiple) {
          this.selectModel = [];
          this.selectParent = [];
          this.selectChild = [];
        }
        this.$nextTick(() => {
          this.positionTop = this.$refs["dropInputBox"].offsetHeight;
        });
      }
    },
    dataList(val) {
      if (this.isEdit) {
        this.dataList = val;
        this.setEditData();
      }
    },
  },
  mounted() {
    if (this.isEdit) {
      this.selectModel = this.value;
    }
    if (this.multiple) {
      this.selectModel = [];
      this.selectParent = [];
      this.selectChild = [];
    }
    this.getSubCategories();
  },
  methods: {
    // 删除当前选中
    deleteItem(index) {
      this.selectMutipleName.splice(index, 1);
      this.selectParent.splice(index, 1);
      this.selectChild.splice(index, 1);
      this.selectModel.splice(index, 1);
      this.$nextTick(() => {
        this.positionTop = this.$refs["dropInputBox"].offsetHeight;
      });
    },
    async setEditData() {
      if (this.selectModel && JSON.stringify(this.selectModel) != "{}") {
        let findArr = this.dataList.find((item) => {
          return item.code == this.selectModel.code;
        });
        if (findArr) {
          this.selectName = findArr.name;
          this.selectModel = findArr;
          this.selectParent = findArr;
        } else {
          await this.getSubCategories({ code: this.selectModel.codeP });
          let findP = this.dataList.find((item) => {
            return item.code == this.selectModel.codeP;
          });
          let findC = this.childList.find((item) => {
            return item.code == this.selectModel.code;
          });
          this.selectName = findP.name + "-" + findC.name;
          this.selectModel = findC.code;
          this.selectParent = findP;
          this.selectChild = findC;
        }
      }
    },
    // 拿到选中的value
    selectItems(item, ite) {
      this.currentItem = this.deepClone(item);
      if (this.multiple) {
        if (ite) {
          this.selectModel.push({
            name: item.name,
            code: item.code,
            childName: ite.name,
            childCode: ite.code,
          });
          this.selectChild.push(this.deepClone(ite));
          let findItem = this.selectParent.find((val) => {
            return val.code == item.code;
          });
          if (findItem) {
            if (this.selectMutipleName.code == item.code) {
              this.selectMutipleName.splice(0, 1, {
                code: ite.code,
                name: item.name + "-" + ite.name,
              });
            } else {
              let finds = this.selectMutipleName.find((val1) => {
                return val1.code == ite.code;
              });
              if (!finds) {
                this.selectMutipleName.push({
                  code: ite.code,
                  name: item.name + "-" + ite.name,
                });
              }
            }
          }
        } else {
          let finds = this.findItems(this.selectMutipleName, item);
          if (!finds) {
            this.currentIndex++;
            this.selectModel.push(this.deepClone(item));
            this.selectParent.push(this.deepClone(item));
            this.selectMutipleName.push(this.deepClone(item));
          }
          if (this.childList.length > 0) {
            this.childList = [];
            this.selectChild = [];
          } else {
            this.getSubCategories(item);
          }
        }
        this.$nextTick(() => {
          if (this.$refs["dropInputBox"].offsetHeight > 34) {
            this.positionTop = this.$refs["dropInputBox"].offsetHeight;
          }
        });
      } else {
        if (ite) {
          this.selectName = item.name + "-" + ite.name;
          this.selectModel = this.deepClone(ite);
          this.selectModel.codeP = item.code;
          this.selectModel.nameP = item.name;
          this.selectChild = this.deepClone(ite);
          this.selectModel.isChild = true;
          this.isShowSelect = false;
        } else {
          this.selectModel = this.deepClone(item);
          this.selectParent = this.deepClone(item);
          this.selectName = item.name;
          if (this.childList.length > 0) {
            this.childList = [];
            this.selectChild = [];
          } else {
            this.getSubCategories(item);
          }
        }
      }
      this.$emit("change", this.selectModel);
    },
    findItems(obj, val) {
      let finds = obj.find((item) => {
        return item.code == val.code;
      });
      return finds;
    },
    // 列表item鼠标移入颜色加深
    selectItemEnter(child, index, ind) {
      if (!child) {
        this.onHover = true;
        this.activeIndex = index;
        this.activeChildIndex = ind;
      } else {
        this.onChildHover = true;
        this.activeIndex = index;
        this.activeChildIndex = ind;
      }
    },
    // 移除颜色加深
    selectItemLeave(child) {
      if (!child) {
        this.onHover = false;
        this.activeIndex = -1;
        this.activeChildIndex = -1;
      } else {
        this.onChildHover = false;
        this.activeIndex = -1;
        this.activeChildIndex = -1;
      }
    },
    // 是否显示下拉框
    activeDrop() {
      this.isShowSelect = !this.isShowSelect;
    },
    // 点击空白处关闭下拉框
    handleClose() {
      this.isShowSelect = false;
    },
     // 判断当前item是否是选中状态
    isSelected(item, key = "") {
      let status = false;
      if (this.multiple) {
        if (
          key == "parent" &&
          this.selectParent &&
          this.selectParent.length > 0
        ) {
          status = this.selectParent.find((ite) => {
            return item.code == ite.code;
          });
        } else if (
          (key = "child" && this.selectChild && this.selectChild.length > 0)
        ) {
          status = this.selectChild.find((ite) => {
            return item.code == ite.code;
          });
        }
      } else {
        if (key == "parent") {
          status = item.code == this.selectParent?.code;
        } else {
          status = item.code == this.selectChild?.code;
        }
      }
      return status ? true : false;
    },
     // 获取下拉框数据
    async getSubCategories(datas) {
      try {
         // 如果传入父级的code那么会根据父级code查询对应子级
         // 默认传code'3131',查询到的是所有父级数据
        const params = {
          categoryCode: datas?.code ? datas.code : "3131",
          channelCode: "INT",
        };
        const { data } = await querySubCategories(params);
        if (datas?.code) {
          this.childList = data;
        } else {
          this.dataList = data;
        }
      } catch (error) {
        console.error(error);
      }
    },
  },
};
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322

# 样式

<style lang="scss" scoped>
.dropDown-container {
  position: relative;
  .select-input {
    width: 336px;
    font-size: 12px;
    position: relative;
    .select_content {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      width: 336px;
      max-height: 66px;
      border: 1px solid #dcdfe6;
      background-color: #fff;
      border-radius: 4px;
      &::-webkit-scrollbar {
        position: absolute;
        top: 0px;
        right: 0;
        width: 5px;
      }
      &::-webkit-scrollbar-thumb {
        background-color: #e8e9ea;
        height: 80px;
        border-radius: 3px;
      }
      .el-tag {
        margin: 2px 0 2px 6px;
        height: 24px;
        line-height: 24px;
      }
      .select-input__inner {
        flex-grow: 1;
        border: none;
        // margin-left: 15px;
      }
    }
    .select-input__inner {
      width: 336px;
      height: 32px;
      line-height: 32px;
      background-color: #fff;
      background-image: none;
      border-radius: 4px;
      border: 1px solid #dcdfe6;
      color: #606266;
      display: inline-block;
      outline: 0;
      padding: 0 15px;
      -webkit-transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
      transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
      cursor: pointer;
      &::-webkit-input-placeholder {
        color: #caced4;
        font-size: 13px;
      }
      &:focus {
        border-color: #409eff;
      }
    }
    .select-icon {
      position: absolute;
      top: 0;
      right: 5px;
      height: 100%;
      -webkit-transition: all 0.3s;
      border-left: 1px #eaedf2 solid;
      color: #c0c4cc;
      text-align: center;
      pointer-events: all;
      .icon {
        height: 100%;
        width: 25px;
        color: #c0c4cc;
        font-size: 14px;
        -webkit-transition: -webkit-transform 0.3s;
        transition: -webkit-transform 0.3s;
        transition: transform 0.3s;
        transition: transform 0.3s, -webkit-transform 0.3s;
        transition: transform 0.3s, -webkit-transform 0.3s;
        -webkit-transform: rotateZ(180deg);
        transform: rotateZ(180deg);
        cursor: pointer;
        &::after {
          content: "";
          height: 100%;
          width: 0;
          display: inline-block;
          vertical-align: middle;
        }
      }
    }
  }
  .scroll {
    overflow-y: scroll;
    overflow-x: hidden;
  }
  .isError {
    .select-input__inner {
      border-color: #f56c6c;
    }
  }
  .selectList-box {
    opacity: 0;
    -webkit-transform: scaleY(0);
    transform: scaleY(0);
    min-width: 320px;
    position: absolute;
    top: 33px;
    left: 0;
    transform-origin: center top;
    z-index: 2001;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    background-color: #fff;
    -webkit-box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
    box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    margin: 5px 0;
    margin-top: 12px;
    overflow: hidden;
    .selectList-wrap {
      margin-bottom: -17px;
      margin-right: -17px;
      overflow: scroll;
      height: 100%;
      max-height: 274px;
      .select-list {
        list-style: none;
        padding: 6px 0;
        margin: 0;
        -webkit-box-sizing: border-box;
        box-sizing: border-box;
        .select-list-item {
          font-size: 14px;
          font-weight: 500;
          padding: 0 20px;
          position: relative;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          color: #666666;
          height: 34px;
          line-height: 34px;
          -webkit-box-sizing: border-box;
          box-sizing: border-box;
          cursor: pointer;
          span {
            display: inline-block;
            width: 100%;
          }
          .select-label {
            z-index: -1;
            display: inline-block;
            width: 120%;
            height: 34px;
            position: absolute;
            left: -22px;
          }
          .child-list {
            .child-list-item {
              .select-child-label {
                z-index: -1;
                display: inline-block;
                width: 120%;
                height: 34px;
                position: absolute;
                left: -22px;
              }
            }
          }
          .onHover {
            background: #f6f7fb;
          }
        }
        .hasChild {
          height: auto;
        }
        .selected {
          color: #409eff;
          font-weight: 700;
        }
      }
    }
  }
  .selectReverse {
    -webkit-transform: rotateZ(0) !important;
    transform: rotateZ(0) !important;
  }
  .selectActive {
    opacity: 1;
    -webkit-transform: scaleY(1);
    transform: scaleY(1);
    -webkit-transition: opacity 0.3s cubic-bezier(0.23, 1, 0.32, 1),
      webkit-transform 0.3s cubic-bezier(0.23, 1, 0.32, 1);
    transition: opacity 0.3s cubic-bezier(0.23, 1, 0.32, 1),
      webkit-transform 0.3s cubic-bezier(0.23, 1, 0.32, 1);
    transition: transform 0.3s cubic-bezier(0.23, 1, 0.32, 1),
      opacity 0.3s cubic-bezier(0.23, 1, 0.32, 1);
    transition: transform 0.3s cubic-bezier(0.23, 1, 0.32, 1),
      opacity 0.3s cubic-bezier(0.23, 1, 0.32, 1),
      -webkit-transform 0.3s cubic-bezier(0.23, 1, 0.32, 1);
    -webkit-transform-origin: center top;
    transform-origin: center top;
  }
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209

# 数据结构

dataList:

{
    "data": [
        {
            "code": "0001",
            "name": "商品1"
        },
        {
            "code": "0002",
            "name": "商品2"
        },
        {
            "code": "0003",
            "name": "商品3"
        },
        {
            "code": "0004",
            "name": "商品4"
        },
        {
            "code": "0005",
            "name": "商品5"
        }
    ]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24

childList:

{
    "data": [
        {
            "code": "00011",
            "name": "商品6"
        },
        {
            "code": "00012",
            "name": "商品7"
        },
        {
            "code": "00013",
            "name": "商品8"
        },
        {
            "code": "00014",
            "name": "商品9"
        },
        {
            "code": "00015",
            "name": "商品10"
        }
    ]
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
在GitHub上编辑 (opens new window)
#vue
上次更新: 2/23/2022, 5:36:03 PM

← 使用el-select,出现切换数据后item消失的问题 给按钮加上权限校验后导致v-if失效的问题→

最近更新
01
createElement函数创建虚拟DOM
05-26
02
clipboard 剪切板属性
05-26
03
vue的权限管理
05-16
更多文章>
Theme by Vdoing | Copyright © 2021-2022 Xin | MIT License
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式
×